Center horizontally
(1) Using inline-block+text-align
<div class= "Parent" >
<div class= "Child" >demo</div>
</div>
. Child {Display:inline-block; }. Parent {Text-align:center} principle: The Sub-box is first changed from block-level element to inline block element, and then centered by setting the inline block element to center horizontally. Pros: Good compatibility, even compatible with IE6, IE7 (2) Use Table+margin. Child {display:table margin:0 auto; } principle: First set the sub-frame as a block-level table to display, and then set the sub-box centered to achieve horizontal center. Cons: Do not support IE6, IE7, change div to table (3) using Absolute+transform. Child {Position:absolute; left:50%; Transform:translatex (-50%)} . Parent {Position:relative} disadvantage: Transform belongs to CSS3 content, compatibility has some problems, the high-version browser needs to add some prefixes (4) using Flex+margin . Child {margin:0 Auto}. Parent {Display:flex} disadvantage: Low version browser (IE6 IE7 IE8) not supported (5) Use Flex+justify-content. parent {Display:flex; Justify-content:center} Disadvantage: The lower version of the browser (IE6 IE7 IE8) does not support vertical centering (1) using Table-cell+vertical-align. Parent { Display:table-cell; vertical-align: Middle} (2) using Absolute+transform. Child {Position:absolute; top:50%; Transform:translatey (-50%)} . Parent {Position:relative} disadvantage: Transform belongs to CSS3 content, compatibility has some problems, the high-version browser needs to add some prefixes (3) using Flex+align-items . parent {Position:flex; Align-items:center; The horizontal vertical Center (1) uses absolute+transform (unknown height). parent {position:relative; }. Child {Position:absolute; left:-50%; top:-50% transform:tranplate ( -50%,-50%)} (1.1) Use Absolute+transform (known height). parent {position:relative; }. Child {Position:absolute; width:100px; height:100px; left:-50%; top:-50% margin: -50px 0 0-50px; } (2) use Inline-block+text-align+table-cell+vertical-align. Parent {text-align:center; Display:table-cell; Vertical-align:middle; }. Child {Display:inline-block; } Pros: Better compatibility (3) Use Flex+justify-content+align-items. Parent {Display:flex; Justify-content:center; Align-items:center; Disadvantage: There are some problems with compatibility
Several ways to center horizontally vertically in CSS