(行内元素)line-height设置为父元素的高度
只适用单行文本, 多行将会跑出父元素外
(行内元素)vertical: middle;
给要居中的元素加个行级兄弟元素,如img,input,
使此元素height:100%,width:0,撑满父元素,然后给居中元素设置vertical-align:middle;
如果是span,a标签的兄弟元素只能设定行高line-height为固定父元素高度,不能为100%!
top: 50%再向上移动元素一半的高度
只适用于高度已知的元素,并要使用绝对定位position:absolute,
top:50% , 再加 margin-top: 元素一半的高度的负值
margin: auto; (这个方法非常神奇)
这个方法使用了一个 position:absolute,有固定宽度和高度的 div。这个 div 被设置为 top:0; bottom:0;(水平居中则再设置left:0;right:0;)。但是因为它有固定高度,其实并不能和上下都间距为 0,因此 margin:auto; 会使它居中。使用 margin:auto;使块级元素垂直居中是很简单的。
content { position:absolute; top:0; bottom:0; left:0; right:0; margin:auto; height:240px; width:70%;}
优点:简单
缺点:IE8以下无效,无足够空间时,content 被截断,但是不会有滚动条出现
div {
height:300px;
width:300px;
background:#000;
position:absolute;
top:0;
bottom:0;
left:0;
right:0;
margin:auto;
}
加50%高度的空div:
高度H已知,但不采用绝对定位,
让要居中的元素前面加个div 高度为50%父元素高度,再将要居中的元素margin-top:-H/2px;
单元格属性( table-cell)
父元素设置display:teble-cell即可让子元素垂直居中
行内元素水平居中:text-align:center;
块级元素水平居中:margin:auto