[Known width and height]
- Width and height are known [parent element positioned opposite the sub-element absolute positioning top left margin-top margin-left]
.box { position: relative; width: 300px; height: 300px; border: 1px solid #000; } .center { background-color: red; width: 100px; height: 100px; position: absolute; top: 50%; left: 50%; margin-top: -50px; margin-left: -50px; }
2 has been known to the aspect [parent element located opposite, top sub-element absolute positioning is 0, bottom to 0, left is 0, right is 0, margin of auto]
.box{ width:300px; height:300px; border:1px solid black; position: relative; } .center{ background: red; width:100px; height:100px; margin:auto; bottom: 0; top:0; left:0; right:0; position: absolute; }
[Width High Unknown]
1. The width and height unknown [CSS3 the transform, absolute positioning, top was 50%, left was 50%] transform only compatible to IE9
.box{ width:300px; height:300px; border:1px solid black; position: relative; } .center{ background: red; position: absolute; top: 50%; left: 50%; transform: translate(-50%,-50%) }
2. The width and height unknown [Flex layout, justify-content: center; align-items: center;] flex only compatible to IE10
.box{ width:300px; height:300px; border:1px solid black; display: flex; justify-content: center; align-items: center; } .center{ background: red; }
There are two cases:
Case 1: content, but more, but to achieve vertical and horizontal centering Case 2: too much content, it can only achieve vertical centering (if you want to achieve horizontal and vertical centering, require fixed-width)