The best and most flexible way
The main trick in this demo is that in the normal flow of elements going from top to bottom, so the margin-top: auto
is set to zero. However, an absolutely positioned element acts the same for distribution of free space, and similarly can be centered vertically at the specified top
and bottom
(does not work in IE7).
##This trick will work with any sizes of div
.
div {
width: 100px;
height: 100px;
background-color: red;
position: absolute;
top:0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
}
<div></div>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…