Method One: Position plus margin (compatibility: supported by mainstream browsers, IE6 not supported) The easiest to understand is also the most common way
<div class= "box" > <div class= "center" ></div></div>
/**css**/.box { width:600px; height:600px; Background: #000; position:relative;. Center { Position:absolute; width:100px; height:100px; Background:orange; left:0; right:0; top:0; bottom:0; Margin:auto;}
Another kind of margin+position
<div class= "box" > <div class= "center" ></div></div>
/**css**/. Box{width:600px;Height:600px;background:#000;position:relative;. Center {position:Absolute;width:100px;Height:100px;background:Orange; Left:50%;Top:50%;margin-left:-50px;
margin-top:-50px;
}
Method Two: Position plus transform (compatibility: IE9 below does not support transform, mobile phone port is better. )
/* CSS */.box { position:relative; Background: #ccc; width:600px; height:600px;} . center { Position:absolute; Background:green; top:50%; left:50%; Transform:translate ( -50%,-50%); width:100px; height:100px;}
Method Three: Display:flex;margin:auto
/* CSS */.box { background:yellow; width:600px; height:600px; Display:flex; }. Center { Background:green; width:100px; height:100px; Margin:auto;}
Method Four: Not fixed width height (IE67 not supported)
. box { background:yellow; width:600px; height:600px;}
. Content {
left:50%;
Transform:translatex (-50%);
display:table-cell;//Container Variable cell
vertical-align:middle;//Cell Center
}
Method Five: Similar to method four
/*CSS*/. Box{width:200px;Height:200px;background:Yellow;Display:Table-cell;vertical-align:Middle;text-align:Center;}. Center{Display:Inline-block;vertical-align:Middle;width:100px;Height:100px;background:Green;}
Method Six: Pure position
/* CSS */.box { background:yellow; width:200px; height:200px; Position:relative;}. Center { Background:green; Position:absolute; width:100px; height:100px; left:50px; top:50px; }
Method Seven: Flex;align-items:center;justify-content:center
. box { background:yellow; width:600px; height:600px; Display:flex; Align-items:center; Justify-content:center;} . center { Background:green; width:100px; height:100px;}
In the middle of the way online there will be many ways, skilled in one or two of them are enough.
Mobile Recommendations You use the method four and seven not fixed width, the effect is very good;
PC-side words are recommended to use pure position because of the low version of the browser to consider compatibility issues. I hope you have some help!
Multiple ways to center your container horizontally