Record collection is pure CSS The level of level realization 、 The vertical centering method can be used at the block level 、 Fast in business 、 Inline elements and text images, etc .

  1. Horizontally or vertically centered  
    1.1 text-align
    1.2 margin
    1.3 line-height
    1.4 padding
  2. Center horizontally and vertically at the same time
    2.1 Baffle way to achieve the horizontal and vertical center
    2.2 vertical-align
    2.3 Simulate cell properties
    2.4 position + margin: negative
    2.5 position + margin:auto
    2.6 position + translate
    2.7 position + calc
    2.8 be relative to viewport Do horizontal and vertical centring
    2.9 css3 - flex
  3. Picture related horizontal vertical center
    3.1 Background mode
    3.2 CSS expression
    3.3 button The way
    3.4 NetEase NEC - The way to fit the picture

1. Horizontally or vertically centered

1.1 text-align

It's not very demanding , And the content is a text element or an inline block element (inline-block), It's easy to get through text-align:center Center horizontally .
Example :

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<style>
div{
background:#eee;
text-align: center;
}
span{
display:inline-block;
background:#aaa;
width: 200px;
}
</style>
</head>
<body>
<div>
Use text-align:center Center horizontally <br/>
<span>inline-block</span>
</div>
</body>
</html>

1.2 margin

For content, it's a block level element , adopt  margin:0px auto  It's easy to center horizontally .
Example :

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<style>
div{
background:#eee;
text-align: center;
}
p{
background:#aaa;
width:500px;
line-height:100px;
margin:0px auto;
}
</style>
</head>
<body>
<div>
<p>MARGIN:0PX AUTO</p>
</div>
</body>
</html>
advantage shortcoming
Simple and intuitive Elements centered horizontally must have a fixed width

1.3 line-height

When the content is plain text or in line fast elements , The simplest is to set up  line-height  Achieve vertical centering , However, there are many shortcomings in this way , First, the value of row height must be the height of the current parent element , Two is , Only one line , There can't be many lines .

advantage shortcoming
Simple and intuitive Can only work on inline elements or inline blocks 、 Only one line, not many lines 、 The value of row height must be the height of the parent element

1.4 padding

If the parent element has no requirement for height , Can be set by  padding-top  And  padding-bottom  For the same value , To achieve the pseudo vertical center effect .
Example :

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<style>
div{
padding:200px 0;
background:#eee;
text-align: center;
}
p{
background:#aaa;
}
</style>
</head>
<body>
<div>
<p>PADDING</p>
</div>
</body>
</html>
advantage shortcoming
It's simple Elements that are pseudo vertically centered cannot have height

2. Center horizontally and vertically at the same time

2.1 Baffle way to achieve the horizontal and vertical center

I call this the baffle way , Because it's very similar in the way it's implemented .
Example :

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.box{
width:600px;
height:600px;
background:#eee;
}
.top{
height:50%; }
.box1{
width:200px;
height:200px;
background:#aaa;
margin:0px auto;
margin-top:-100px; }
</style>
</head>
<body>
<div class="box">
<div class="top"></div>
<div class="box1"></div>
</div>
</body>
</html>
advantage shortcoming
No need to locate You still need to calculate and set the negative margin value
To introduce a waste label

Note:  But in practical use, if we don't consider IE7-, That useless element can be replaced by a pseudo class .

2.2 vertical-align

vertial-align  yes CSS A property of , This attribute only works on inline elements or inline fast elements , It is mainly used to set the vertical alignment between the current element and the adjacent elements at the same level ( Based on the baseline ). It is often used to align pictures with text .
Here is the use of  vertical-align  This alignment To insert a child element of the same height into the parent element , Finally, set... For the child element  vertical-align  Property to align our real content .
It's a clever way , But I think its limitation lies in that it can only act on intra industry or intra industry fast , In addition, insert an irrelevant scrap label , However, the tag can be replaced by a pseudo class .
Most will  text-align:center  And  vertical-align:middle, Use a combination of , We can center the fast elements in the row horizontally and vertically
Example :

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<style>
div{
width:300px;
height:200px;
text-align:center;
background:#eee;
text-align:center;
}
div:after{
content:'';
display:inline-block;
width: 1px;
height:100%;
vertical-align:middle;
} </style>
</head>
<body>
<div>
<button>button1</button>
<button>button2</button>
</div>
</body>
</html>

2.3 Simulate cell properties

We know that tables have many features , For example, the associated scaling of width , Another example is the vertical center that we need to use now , And it happens that CSS It can also be done through display The attribute is HTML Elements give properties to table elements .
Common are :
display:table  Declare a form
display:table-row  Declare a line
display:table-cell  Declare a cell .

Simple use examples ( Quick start ):

 <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<style> .table{
display:table;
border:1px solid #ccc; }
.row{
display:table-row;
}
.cell{
display:table-cell;
border:1px solid #ccc;
}
</style>
</head>
<body>
<div class="table">
<div class="row">
<div class="cell">ROW1-CELL1</div>
<div class="cell">ROW1-CELL2</div>
</div>
<div class="row">
<div class="cell">ROW2-CELL1</div>
<div class="cell">ROW2-CELL2</div>
</div>
</div>
</body>
</html>

So by this means , We can also achieve the desired horizontal and vertical centering effect .

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<style>
.box{
display:table-cell;
width:500px;
height:500px;
background:#eee;
vertical-align:middle;
text-align: center;
}
p{
display:inline-block;
background:#aaa;
}
</style>
</head>
<body>
<div class="box">
<p>
TABLE-CELL-TEST<br/>
TABLE-CELL-TEST<br/>
TABLE-CELL-TEST<br/>
</p>
</div>
</body>
</html>
advantage shortcoming
Center multiple lines of content vertically, especially text content Only IE8+ To support
You can only center inline elements vertically 、 Block in row

By simulating the square of a table, the advantage is that you can center multiple lines vertically , But the disadvantage is that at present only IE8+ Only the version of is supported .

2.4 position + margin: negative

Through positioning, you can achieve horizontal and vertical center , However, the requirements for the conditions of use are relatively high , First of all, the content should be absolutely positioned (absolute), The parent element should be positioned relatively (relative), Secondly, the content should have a fixed size , Finally, adjust margin Negative values and offset attribute values .
Example :

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<style>
div{
position:relative;
height:600px;
width:600px;
background:#eee;
} p{
position:absolute;
width:200px;
height:200px;
top:50%;
left:50%;
margin-left:-100px;
margin-top:-100px;
background:#aaa;
}
</style>
</head>
<body>
<div>
<p>MARGIN:0PX AUTO</p>
</div>
</body>
</html>
advantage shortcoming
Application range light
Compatibility is good.
The elements to be centered should have a fixed size
To calculate margin Negative margin value

2.5 position + margin:auto

For the element of absolute positioning , The default effect is :

  • The size will automatically shrink to fit the content .
  • The default location is auto,
  • The default value of margin is 0.

In this case, if the default size , We set the offsets in all four directions to 0 Words , The element automatically stretches in four directions 100% Fit its reference elements . If you set a fixed width again , And set up  margin:auto, Then you can be surprised to find that , The absolutely positioned element is horizontally and vertically centered on the parent element ( Reference elements ) in .

About margin:auto Why can you center the block level horizontally but not vertically
auto It means automatic distribution ,margin:auto, It means to assign margins automatically . But according to CSS2.1 The specification of , The width of a block level element refers to the width of its parent element ( That's why the block level elements occupy a single line ), Only the width is 100%,auto To be able to distribute , Then center the elements horizontally , But the problem is ,CSS The specification also defines that the height of block level elements is adapted to the content , That is to say, the height of block level elements is unknown , So set... For the top and bottom margins auto Of course, it can't be vertically centered . But when we position an element , When you make it a block level element and leave the document stream , At the same time, set up top:0;right:0;bottom:0;left:0, The size of the element will fit its parent element or reference element , namely width:100%,height:100%, Then set up margin:auto, Then we can carry out horizontal / Vertical center .

Example :

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<style> .box{
position:relative;
width:600px;
height:600px;
background:#aaa;
}
p{
position:absolute;
width:200px;
height:200px;
left:0;
right:0;
bottom:0;
top:0;
margin:auto;
background:#eee;
}
</style>
</head>
<body>
<div class="box">
<p>This is Position Advace</p>
</div>
</body>
</html>
advantage shortcoming
The use condition is simple
There is no need to calculate the negative margin value
The elements to be centered should have a fixed size
Only IE8+ Support

2.6 position + translate

adopt CSS3 Of  translate  Achieve the horizontal and vertical center , Its principle and position+margin The way negative values work is very similar .
But compared to margin Negative mode , Its advantages are embodied in :

  • There is no need to set a fixed width for the content .
  • There is no need to manually calculate the negative margin value .

transform:translate(-50%,-50%)  You can automatically move the width of the current element left and up 50%.
Example :

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<style>
div{
position:relative;
height:600px;
width:600px;
background:#eee;
}
p{
position:absolute;
left:50%;
top:50%;
transform:translate(-50%,-50%);
background:#aaa;
} </style>
</head>
<body>
<div>
<p>transForm</p>
</div>
</body>
</html>
advantage shortcoming
You don't need to set a fixed size for the box in the middle
Mobile terminal
Only IE9+ Support

2.7 position + calc

calc()  yes CSS3 Function properties of , Its function is to perform four operations , The values involved in the operation can be relative units , It can also be an absolute unit .
utilize calc The principle of centring is to do this for left:50%,top:50%, And then let 50% Subtract half the width or height of the current element , The mechanism still belongs to the negative margin mode , But compared to the position The negative margin of and translate Methods such as , It mainly reduces the number of style declarations .
Example :

 <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<style> .box{
position:relative;
width:600px;
height:600px;
background:#aaa;
}
p{
position:absolute;
width:200px;
height:200px;
left:calc(50% - 100px);
top:calc(50% - 100px);
background:#eee;
}
</style>
</head>
<body>
<div class="box">
<p>CSS3 - CALC</p>
</div>
</body>
</html>
advantage shortcoming
Reduce style declaration
Mobile terminal
You need to set a fixed size for the centered element
Only IE9+、Chrome19+

2.8 be relative to viewport Do horizontal and vertical centring

CSS3 A new unit of measure is introduced in ,vh And vw, They are based on viewport The relative unit of , namely viewport The width and height of are divided into 100 Equal parts of vh And vw.
in other words :
1vh = 1%(viewport Height )
1vw = 1%(viewport Width )
Then set the size of the current element to 50vh And 50vw That is, half of the height and width of the current window , combining  translate(50%,50%)  You can center the current element horizontally and vertically in the current window .

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<style>
p{
position:absolute;
width:50vw;
height:50vh;
transform:translate(50%,50%);
background:#eee;
}
</style>
</head>
<body>
<div class="box">
<p>CSS3 - CALC</p>
</div>
</body>
</html>
advantage shortcoming
Use in a window based environment Only IE9+ 、Chrome26+、Firefox19+、safair6.0+ Support
Fixed size

2.9 css3 - flex

flex is CSS3 Add powerful layout features , utilize flex We can achieve flexible, convenient and flexible layout scheme .
utilize flex The layout only needs to set two lines of style declaration to realize the horizontal and vertical center of elements .
justify-content:center  Horizontally centered
align-items:center  Vertically centered
Example :

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<style> div{
display:flex;
justify-content:center;
align-items:center;
text-align: center;
background:#eee;
} p{
background:#aaa;
} </style>
</head>
<body>
<div>
<p>FLEX</p>
</div>
</body>
</html>
advantage shortcoming
Mobile  
There is no need to set a fixed size
Compatibility low version IE I won't support it

3 Picture related horizontal vertical center

Special for horizontal and vertical center of picture CSS Method , And the following methods can be compatible in all browsers .

3.1 Background mode

This is the easiest way , It's just taking the picture as the background , Then set the  background-position:center center  Center it horizontally and vertically in the element .

3.2 CSS expression

In this way, we need to use IE Private extension of , And the advantage of this approach is that it can be compatible with IE5.
The disadvantages are obvious , It can only be used for pictures , Because it involves CSS In the expression  this.height.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<style>
.box{
display:table-cell; /* In the advanced browser, the image is vertically centered through the table feature */
width:500px;
height:500px;
vertical-align: middle;
background:#eee;
}
.box img{
display: block;
margin:0px auto;
margin-top:expression((500 - this.height)/2); /* IE Browser proprietary CSS Expression properties */
}
</style>
</head>
<body>
<div class="box">
<img src="http://nec.netease.com/img/s/1.jpg" alt="" />
</div>
</body>
</html>

3.3 button The way

It's a little tricky , But the advantage is that it's compatible with all browsers , But in IE There will be a slight flaw in the browser , That is, when you click , There will be a slight shake in the picture .

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<style>
button{
height:500px;
width:500px;
background:#eee;
border:none;
outline:none;
}
</style>
</head>
<body>
<button>
<img src="http://nec.netease.com/img/s/1.jpg" alt="" />
</button>
</body>
</html>

3.4 NetEase NEC - It's a great way to get pictures

This kind of Netease NEC The way of invention , The advantage is that as long as the size of the image does not exceed the parent element , All images are centered in the parent element .

principle :
First, position the outer box relative to each other , And then absolute positioning for the inner box , And the size is determined by the content ( picture ) open , Then set the offset value for the inner box left:50%;top:50%; Finally, put two of them inside img label , But it's all a picture , One of the images is hidden to make the inner box identify the size , The other picture is used to show , And this picture is absolutely positioned , then left:-50%;top:-50%, In this way, the image can be leveled 、 Vertically centered in the parent element .

Example :

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<style type="text/css">
.box {
position:relative;
width: 600px;
height: 600px;
background:#eee; }
.inner{
position:absolute;
left:50%;
top:50%;
}
.inner .img1{
visibility: hidden;
}
.inner .img2{
position:absolute;
left:-50%;
top:-50%;
}
</style>
</head>
<body>
<div class="box">
<div class="inner">
<img class="img1" src="http://nec.netease.com/img/s/1.jpg" />
<img class="img2" src="http://nec.netease.com/img/s/1.jpg" />
</div>
</div>
</body>
</html>

call ~~ Finally, the blog Park markdown It's changed , I decided to use this style later , I feel like the garden is markdown It's really not easy to use , Not all functions ..


CSS A collection of centering methods (*******************************) More articles about

  1. CSS A collection of centering methods

    Record collection is pure CSS The level of level realization . The vertical centering method can be used at the block level . Fast in business . Inline elements and text images, etc . Horizontally or vertically centered 1.1 text-align 1.2 margin 1.3 line-height 1.4 p ...

  2. CSS The middle way

    css There are many ways to center , Adopt appropriate methods according to the actual situation of the work , We can get twice the result with half the effort . Sort out some common centering methods as follows : The code is as follows : <div class="con"> <d ...

  3. CSS The middle method collects

    Turn from here :http://jinlong.github.io/blog/2013/08/13/centering-all-the-directions/ Compatible with lower versions IE Methods html Use the table structure background ...

  4. css Centering method and double wing configuration

    In the middle type Method Corresponding attribute level vertical level & vertical 1. The parent element uses the outer margin to automatically 2. Child elements show block level elements within a row , Write content , The parent element sets the text centered 3. Turn on non absolute and fixed positioning for the parent element, and turn on absolute positioning for the child element ...

  5. css Summary of centering method

    Horizontal center Inline elements If the element is set to text . In line elements such as pictures , The horizontal center is set to the parent element by text-align:center To achieve . Blocky element When the element is set to Blocky element Time use text-align: ...

  6. css Detailed explanation of centering method

    Horizontal center : By setting the parent element , Center the contents of the child elements :text-align:center; By setting the child element itself , Center the child elements :margin:0 auto; The prerequisite for the above method to work is that the child element is not float Elemental shadow ...

  7. css The middle way

    Vertical center utilize “ The spirit element ”(ghost element) Technology to achieve vertical center , That is, put a 100% High pseudo elements , Align text and pseudo elements vertically , So as to achieve the purpose of vertical center . .ghost-center { po ...

  8. CSS Summary of all kinds of centering methods

    When developing front-end pages , The centering of elements is a problem that can never be solved . The seemingly simple middle word , In fact, there are many situations , There are many ways to deal with it , This paper attempts to summarize the problem of centering in page layout ~~ The problem of center is divided into horizontal center and vertical center ...

  9. CSS The middle way to integrate -- Horizontal center

    original text CSS The middle of the problem , It's a platitude , All kinds of centering methods emerge in endlessly . Is it horizontally or vertically centered ? yes block still inline? Whether the center object is one or more ? Whether the length and width are determined ? And so on, all kinds of factors determine . Here's how it works ...

Random recommendation

  1. Control UI: StateTrigger

    VisualState And StateTrigger Example 1. Customize  StateTriggerControls/UI/VisualState/MyDeviceFamilyStateTrigger.cs ...

  2. use TCGA Collected mRNA Expression data for differential expression

    Do differential expression Software DEseq and edgeR The required data format must be original counts, after normalization and log2 The data after that are not suitable for , So for children's shoes that do differential expression calculation, you can use ExperimentHub Next ...

  3. wordpress The editor made a mistake Warning: scandir() has been disabled for security reasons in

    stay ubuntu There's one installed below wordpress Program , I didn't do anything backstage , When editing a topic , Found the following error in the page . notice: /home/wwwroot/test.localhost/wordpress ...

  4. Calculate any number of Pi

    When using the program to achieve pi The value of , Maybe you can write the algorithm very quickly ( Make use of pi A couple of formulas for ), But because of using a single variable to save the results , The scope of variable representation is limited by computer hardware , therefore , At most, we can only calculate pi The value is more than ten decimal places . But you need to get a bigger position ...

  5. [ turn ]OPENSOLARIS 2009.06 REPOSITORY ISO IMAGES NOW AVAILABLE

    Source: http://hosam.wordpress.com/2009/07/25/opensolaris-2009-06-repository-iso-images-now-availabl ...

  6. Programming language and C Introduction to language

    1. What is a program Command the computer to do what we want it to do , And a set of instructions executed in sequence 2. What is the function of the program Command computer work 3. The characteristics of the program 1. A program is executed line by line 2. It's a language to communicate with computers 3. The program is made up of ...

  7. mysql Common basic operation syntax ( Two )~~ Add, delete and modify the table 【 Command line mode 】

    1. Modify the name of the table :alert table oldtablename rename newtablename; perhaps alert table oldtablename rename to newtablena ...

  8. docker Deploy jira Cracked versions

    1. Make Dockerfile FROM cptactionhank/atlassian-jira-software:7.12.0 USER root # Add the agent crack package to the container COPY "a ...

  9. Doctrine2- Basic concepts

    Several requirements of using framework to operate database 1. Security , For example, to prevent sql Injection, etc. ,pdo Inside prepare,execute Can 2. performance , Database operation is the most basic operation , Frequent use , Implementation efficiency needs to be considered 3.ORM(objec ...

  10. mysql database user surface host Field % problem

    Search for : mysql database user surface host Field % problem Connect :http://blog.csdn.net/xiaomengh/article/details/48706149 stay mysql In the database , Use ...