Structure:
1 < class= "parent">2 <class = "Child" > DEMO</div>3 </div>
Style:
1. Programme 1. Text-align + inline-block (valid for inline elements)
. parent { Background-color:grey; width:500px; Text-align:center; } . Child { display:inline-block; Background-color:skyblue; } /* Content inherits the center of the parent element, and if not, set it separately text-align:left*/
2. Programme 2. Table + margin
1 . Child {2 display:table;/* behaves like a block element, but the width of the table varies with content */3 margin:0 auto; 4 5 Background-color:skyblue; 6 }7 /* Pros: Set child only, no relationship to Parent's style, ie8+ support display:table8 Cons: Incompatible IE678, change structure directly to table*/
3. Programme 3. Absolute + transform
1 . Parent {2 position:relative;3 }4 . Child {5 position:absolute;/* out of document Flow * /6 left:50%;/*% relative to container * /7 Transform:translatex (-50%);/*% relative to itself */8 9 Background-color:skyblue;Ten } One /* Pros: Centering elements do not affect other elements ACons: Incompatible ie678*/
4. Programme 4. Flex + justify-content
1 . Parent {2 Display:flex; 3 justify-content:center;/* Setting the alignment of Flex-item in the horizontal direction */4 }5 /* Pros: Just set the. Parent Style 6 Cons: Incompatible ie678*/
Or:
. Parent {
Display:flex;
}
. Child {
margin:0 Auto;
}
Layout-center horizontally