Center horizontally and center vertically
Solution 1
| Location |
Attribute name |
Value |
Meaning |
| Parent div |
Text-align |
Center |
Center child elements |
| Sub-div |
Display |
Inline-block |
Objects can be presented as inline objects, but the content of objects is presented as block objects. The width of the inline-block is the text width. |
| Sub-div |
Text-align |
Left |
The text in the child element does not inherit the text-align: center attribute of the parent div, and is set to the default text-align: left |
<! DOCTYPE html>
Solution 2
| Location |
Attribute name |
Value |
Meaning |
Compatibility |
| Sub-div |
Display |
Table |
The table is very similar to the block, but it is different from the block element. "The width also follows the content 』 |
IE8 or above |
| Sub-div |
Margin |
0 auto |
The value of Up or down is about 0 and is "automatic 』 |
|
<! DOCTYPE html>
Solution 3: absolute positioning + transform
| Location |
Attribute name |
Value |
Meaning |
Compatibility |
| Parent div |
Position |
Relative |
Sets the parent element as a reference object. |
|
| Sub-div |
Position |
Absolute |
Absolute positioning. The width is determined by the content. |
|
| Sub-div |
Left |
50% |
Set the left edge of the sub-div to the right of the left edge of the parent element. The width of the parent element is 50%: |
|
| Sub-div |
Transform |
0 auto |
The value of Up or down is about 0 and is "automatic 』 |
Newly Added css3, not supported by earlier IE versions |
<! DOCTYPE html>
Disadvantage: The transform attribute is added to css3 and cannot be used in earlier IE versions (IE6, 7, and 8.
Solution 4
| Location |
Attribute name |
Value |
Meaning |
Compatibility |
| Parent div |
Display |
Flex |
When the display of the parent element is flex, the child element naturally becomes a flex item. By default, the flex width is auto. |
|
| Parent div |
Justify-content |
Center |
The project is located in the center of the container. |
|
| Or |
|
|
|
|
| Sub-div |
Margin |
0 auto |
|
|
<! DOCTYPE html>
Alternatively, set the margin attribute in the sub-element: the upper and lower values are 0, and the left and right sides are automatically (centered)
<! DOCTYPE html>
Same effect
Disadvantage: flex is not supported in earlier IE versions.