HTML垂直居中布局
垂直居中布局就是指当前元素在父元素容器中,垂直方向是居中显示的
实现方法:
- table-cell+ vertical-align属性配合使用
- absolute + transform 属性配合使用
table-cell+ vertical-align
设置display: table-cell;
父元素设置为单元格
再使用vertical-align: middle;
设置为垂直方向对齐方式
.parent {
width: 200px;
height: 600px;
background-color: antiquewhite;
display: table-cell;
/*
display属性:
table:设置当前元素为<table>元素
table-cell:设置当前元素为<td>元素(单元格)
*/
vertical-align: middle;
/*
vertical-align属性:用于设置文本内容的垂直方向对齐方式
top:顶部对齐
middle:居中对齐
bottom:底部对齐
*/
}
.son {
width: 200px;
height: 200px;
background-color: brown;
}
<!--定义一个父元素-->
<div class="parent">
<!--定义一个子元素-->
<div class="son">
居中对齐
</div>
</div>
优点:
浏览器兼容器比较好
缺点:
vertical-align
属性具有继承性,会导致父元素的文本也是居中显示的
如果父元素中包含除子元素外的内容的话,就不大适用
absolute + transform
利用移动,同HTML水平居中里的absolute + transform
原理一样
.parent {
width: 200px;
height: 600px;
background-color: antiquewhite;
position: absolute;
}
.son {
width: 200px;
height: 200px;
background-color: brown;
position: absolute;
top: 50%;
transform: translateY(-50%);
}
body
同上个方法
优点:
父元素是否脱离文档流,不影响子元素垂直居中效果
缺点:
transform
属性是CSS3 中的新增属性,浏览器的支持情况可能会不好