Summarizes several ways of CSS centering, note:* for the common way, "wrap" for the container, "div" for the element to be centered.
* 1. absolute positioning , width and height are known to the following code can be implemented, or can be used negative margins;
. div {
width:200px;
height:200px; Margin:auto; Position:absolute; top:0; left:0; bottom:0; right:0; }
2. Do not know the width of the element, only the implementation of a DIV is its parent 1/2, horizontal vertical Center, with the size of the parent element, such as scaling or shrinking.
. div{ Position:absolute; left:30%; right:30%; top:25%; bottom:25%;}
* 3.translate, width known, height unknown case
. wrap{ width:200px;//can also not write, the default account for the total width of the 50% Position:absolute; top:50%; left:50%; Transform:translate ( -50%,-50%);
-webkit-transform:translate ( -50%,-50%);}
4.Table-cell, Div itself highly unknown, only to achieve vertical centering of the case, PS, this case div width is 100%
. wrap{//outer container display:table;}. div{//Inner layer container Display:table-cell; Vertical-align:middle; }
* 5.Flex Layout , if the width is not fixed, just set the Display:flex in the parent container.
. wrap{ Display:flex; Display:-webkit-flex; Justify-content:center;
6.hack method, good to use: after.
. wrap { text-align:center; Overflow:auto; } . Wrap:after, . div { display:inline-block; Vertical-align:middle; } . Div:after { content: '; height:100%; Margin-left: -0.25em; /* need to adjust according to different font size * /}. Wrap { max-width:99%;/* Prevents the document from going to the top of the container when it is too long * /Max-width:calc (100%-0.25em)/* on LY for ie9+ */
Several vertical horizontal centering methods of CSS