In the last interview, the interviewer asked about fixed width and variable width. Then I summarized all the relevant CSS centering
Original excerpt from me Welcome to our front-end blog
http://www.hacke2.cn
Horizontally centeredNest inline elements in a DIV, and Set the following styles in DIV
a{ text-align: center; }
For fixed-width block-level elements, we need to set margin-top and margin-right as auto
.center{ margin: 0 auto; }
Multiple block-level elements, we set their display to inline-block; then Set the attributes of the parent element
div{ text-align: center; }
Set the display of the parent element of the block element that needs to be horizontally centered to flex. And the justify-content attribute is center
body{ display: flex; justify-content: center; }
Set the height and line-height of the inline element to be consistent
a{ height: 200px; line-height:200px; }
If there are too many lines of text in the inline elements, set display: table-cell;vertical-align: on the parent element: middle;
.container{ width: 300px; height: 300px; display: table-cell; vertical-align:middle; }
Set the block-level element to absolute positioning, top to 50%, margin-top:-height/ 2
div{ height: 100px; position: absolute; top: 50%; margin-top: -50px; padding:0; }
Use CSS translate to set the block-level element to absolute positioning, top to 50%, transform: translateY(- 50%);
div{ position: absolute; top: 50%; transform: translateY(-50%); padding:0; }
Set absolute positioning for block-level elements, top is 50%, left: 50%;margin-top:-height/2;margin-left:-width/2
div{ width: 150px; height: 150px; position: absolute; top: 50%; left: 50%; margin-top: -75px; margin-left: -75px; }
Use flex layout for the parent
div{ display: flex; justify-content:center; align-items: center; }
Use CSS translate
div{ position:absolute; top:50%; left:50%; -webkit-transform:translate(-50%,-50%); -moz-transform:translate(-50%,-50%); transform:translate(-50%,-50%); }