Center Horizontally
in-line elements
If the element is set to an inline element, such as text, picture, and so on, the horizontal center is implemented by setting the Text-align:center for the parent element.
block Element
When the element is set as a block element, the use of Text-align:center does not work, then there are two cases: fixed-width block elements and variable-width block elements.
fixed-width block element: The width of the block element is constant。
Elements that satisfy a fixed width and block of two conditions can be centered by setting the left and right margin value to "auto".
In the actual work we will encounter the need to set the "block element of the indefinite width" center, such as page navigation on the pages, because the number of paging is indeterminate, so we can not set the width to limit its elasticity. (Indefinite wide block element: the width of the block element is not fixed.) )
indeterminate wide block element: Width of the block element is not fixed。
Set position:relative and left:50%: Use relative positioning to offset the element to the left by 50%, that is, to achieve the center.
By setting float to the parent element, and then setting position:relative and left:50% to the parent element, the child elements are set position:relative and left:-50% to achieve horizontal centering.
. Container{float: Left;position:relative; Left:50%}. Container ul{List-style:None;margin:0;padding:0;position:relative; Left:-50%;}. Container Li{float: Left;Display:inline;Margin-right:8px;}
<Divclass= "Container"> <ul> <Li><ahref="#">1</a></Li> <Li><ahref="#">2</a></Li> <Li><ahref="#">3</a></Li> </ul></Div>
Center vertically
single line of text for parent element height determination
The height of the parent element determines the vertical centering of a single line of text by setting the height of the parent element and the line-height to a high consistency. (Height: The height of the element, Line-height: As the name implies, row height (line spacing), refers to the distance between the line and the baseline in the text).
multi-line text with parent element height determination
Set the line-height equals height value to the parent element, Font-size set to 0, add a div parent element to the multiline text, and change the element settings Display:inline-block;vertical-align:middle , and reset Font-size and Line-height, because these two properties inherit the value of the parent element.
{ border:1px solid red; line-height: 200px; height:200px; font-size:0; text-align: center;} { display: inline-block; Vertical-align: Middle; font-size:14px; line-height: 20px;}
<Divclass= "Out"> <Divclass= "inner"> <P>111</P> <P>222</P> </Div></Div>
The flex layout of the CSS3 makes it easier to center the problem, and as you become familiar with and understand the flex layout, you will continue to refine this part of the content.
CSS Centering Method Summary