镜像文章:在不确定自身宽度的情况下,用 CSS 实现元素水平居中的2种方法
1.不知道自己高度的情况下, 利用绝对定位只需要以下三行(推荐)
<div class="parentElement">
<div class="childElement">子元素垂直居中</div>
</div>
<style>
.parentElement{
position: relative;
height: 200px;
background: blanchedalmond;
}
.childElement{
position: absolute;
top: 50%;
transform: translateY(-50%);
}
</style>
2.若父容器下只有一个元素,且父元素设置了高度,则只需要使用相对定位即可
<div class="parentElement">
<div class="childElement">子元素垂直居中</div>
</div>
<style>
.parentElement{
height:200px;
background: blanchedalmond;
}
.childElement {
position: relative;
top: 50%;
transform: translateY(-50%);
}
</style>
3.不考虑兼容老式浏览器的话,用Flex布局简单直观一劳永逸
<div class="parentElement">
<div class="childElement">子元素垂直居中</div>
</div>
<style>
.parentElement{
display:flex;/*Flex布局*/
display: -webkit-flex; /* Safari */
align-items:center;/*指定垂直居中*/
height: 200px;
background: blanchedalmond;
}
</style>
4.表格居中,除了IE6/7都支持
<div class="parentElement">
<div class="childElement">子元素垂直居中</div>
</div>
<style>
.parentElement {
display: table;
height: 200px;
background: blanchedalmond;
}
.childElement {
text-align: center;
display: table-cell;
vertical-align: middle;
}
</style>
5.inline-block
<div class="parentElement">
<div class="content">我是内容<br />我也是内容</div>
<div class="actor">我不显示</div>
</div>
<style>
.parentElement {
height: 200px;
background: blanchedalmond;
}
.content {
display: inline-block;
vertical-align: middle;
}
.actor {
display: inline-block;
vertical-align: middle;
height: 200px; /* 和父容器高度相同 */
font-size: 0;
}
</style>