Summarizes several ways of CSS centering, note: * For the common way, "wrap" for the container, "div" for the element to be centered.
* * Absolute positioning, wide and high 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, the width is not fixed, as long as you set the Display:flex in the parent container.
. wrap{ Display:flex; Display:-webkit-flex; Justify-content:center; Align-items: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)/* only fo R ie9+ */ }