As more and more projects are in contact, you can feel the "center" application is very extensive.
Horizontal center, there is not much to say, margin:0 Auto can be solved.
The most disturbing is the vertical centering, which is where this chapter will focus.
Here's a way to divide the vertical center by class:
1. Vertical center of single line text
Code:
Div P { line-height: 30px; height: 30px; }
2. Center image
<Div > < src= "1.jpg" alt= ""/> </ Div >
Div{ width:300px; Border:1px solid red; line-height: 300px; / * Focus */ } div img{ width: 100px; Height: 100px; vertical-align: Middle; / * Focus */ }
3. Table Vertical Center
< Div > < P >This is content</p> </div>
Div { display: table; Border: 1px solid red; height: 100px; width: 300px; } Div p{ display: table-cell; Vertical-align: middle; }
4. Block-level elements are centered vertically
<class= "Blue"> <class= " Red "></div> </div>
. Blue{width:200px;Height:200px;position:relative;Background-color:Blue; }. Red{width:100px;Height:30%;position:Absolute;Top:50%;Margin-top:-15%;/*Margin-top is half the height.*/Background-color:Red; }
Another style notation
. Blue{width:200px;Height:200px;position:relative;/*Focus*/Background-color:Blue; }. Red{width:100px;Height:30%;position:Absolute;/*Focus*/Top:0;/*Focus*/Bottom:0;/*Focus*/margin:Auto;/*Focus*/Background-color:Red; }
5. Use an empty div to center the container vertically
< div class = "Blue" > < div class = "Floater" ></ div > < div class = "Red" ></ div > </ div >
. Blue{Height:200px;width:200px;Background-color:Blue; }. Red{Clear:both;Height:100px;Background-color:Red; }. Floater{float: Left;Height:50%;width:100%;Margin-bottom:-50px;/*half of the content height*/}
6. Use CSS3 to achieve vertical centering
This method is not compatible with IE
<class= "Blue"> <class = "Red" ></ Div > </ Div >
. Blue{width:300px;Height:200px;Display:-webkit-box;/*Focus*/-webkit-box-align:Center;/*Focus*/Background-color:Blue; }. Red{width:100px;Height:100px;Background-color:Red; }
CSS implements a variety of vertical centering methods