Source: http://www.imooc.com/code/6363
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.) )
There are three ways to center a block element with an indefinite width (these three methods are currently used in many ways):
- Add Table Label
- Set the Display:inline method: Similar to the first, the display type is set to the inline element, and the property setting of the variable width element
- Set position:relative and left:50%: Use relative positioning to offset the element to the left by 50%, which is the goal of centering
In this section we'll take a look at the first method:
Why do I add a table label when I choose a method? is to use the length of the table label Adaptive---that does not define its length nor the length of the default parent element body (table whose length is determined by the length of its text), so it can be regarded as a fixed-width block element, and then use the fixed-width blocky-centered margin method to align it horizontally.
First step: Add a table label (including <tbody>, <tr>, <td>) to the center of the element you want to set.
Step two: Set the "left and right margin center" for this table (this is the same as for a fixed-width block element).
Example:
<!DOCTYPE HTML><HTML><Head><MetaCharSet= "Utf-8"><title>Horizontal center of variable width block element</title><style>Table{margin:0 Auto;}/*here is the task area code*/. Wrap{background:#ccc;Display:Table;//Let the second Div become a table margin:0 Auto;//Center display}</style></Head><Body><Div><Table> <tbody> <TR><TD> <ul> <Li>I am the first line of text</Li> <Li>I am the second line of text</Li> <Li>I am the third line of text</Li> </ul> </TD></TR> </tbody></Table></Div><Divclass= "Wrap">set my div container to center horizontally</Div></Body></HTML>
The result of the above code is to center the second DIV element instead of the text inside.
html+css--Horizontal Center Summary (variable width block element method) (i)