Center Horizontally
- margin:0 Auto Dafa
. child{width:100px;margin:0 Auto} Note: A child element must have a width before it can be used
- Display:table Dafa
. child{display:table; margin:0 Auto;}
- Text-align:center Dafa
The normal child element is in the parent element. parent{text-align:center}.child{Display:inline-block} If the parent element is literal, it can not be displayed as inline block elements, because I think the text has inline properties. Parent {Text-align:center}
- Absolute positioning Dafa
. parent{position:relative}.child{position:absolute; left:50%; transform:translate (-50%)} It's amazing!! Oh, yes!! How did I not think!! (1) Positioning if absolute (2) moves to 50%, negative value another:. parent{position:relative}.child{position:absolute; left:50%;margin-left:-element width}// You have to know the width of the child element
- Display:flex Dafa
CSS3 to Be continued
Center Vertically
- Vertical-align Dafa
. parent{Display:inline-block; vertical-align:middle; line-height:200px;}. parent{Display:table-cell; vertical-align:middle; height:200px;} Vertical-align and Line-height (height) are more interesting, control is the parent element, the center is the child element
- Absolute positioning Dafa
. parent{position:relative}.child{position:absolute; top:50%; Transform:translatey (-50%);}
Flex Dafa
Horizontal Vertical CenterSeveral ways are available for reference:. parent{display:table-cell;vertical-align:middle;text-align:center;height:100px;width:200px;}. Child{display:inline-block;} Way two:. parent{position:relative;}. child{position:absolute; top:50%; left:50%; transform:translate ( -50%,-50%);}
CSS: Horizontally centered, vertically centered