我们在进行页面布局时,元素水平垂直居中是必备的布局方式之一,那么下面我们来总结四种我们常见的水平垂直居中的方式,你常常使用哪种呢?
html统一代码
<div class="out">
<div class="inner">
</div>
</div>
table-cell布局
css代码
.out{
width: 400px;
height: 400px;
background-color: pink;
display: table-cell;
vertical-align: middle;
}
.inner{
width: 200px;
height: 200px;
background-color: #bfa;
margin: 0 auto;
}
绝对定位+margin:auto;
.out{
width: 400px;
height: 400px;
background-color: pink;
position: relative;
}
.inner{
width: 200px;
height: 200px;
background-color: #bfa;
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
margin: auto;
}
绝对定位+负magin或2d转换
.out{
width: 400px;
height: 400px;
background-color: pink;
position: relative;
}
.inner{
width: 200px;
height: 200px;
background-color: #bfa;
position: absolute;
left: 50%;
top: 50%;
/* 使用负margin与2d转换皆可 */
/* margin-left: -100px;
margin-top: -100px; */
transform: translate(-50%,-50%);
}
flex布局
使用flex布局此时要注意兼容问题
.out{
width: 400px;
height: 400px;
background-color: pink;
display: flex;
justify-content: center;
align-items: center;
}
.inner{
width: 200px;
height: 200px;
background-color: #bfa;
}
关于实现元素水平垂直居中的四种方式的分享就到这啦。
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。