元素的垂直居中是大家常关注的问题, 今天整理一下元素垂直居中的几种方式.
html结构如下:
<div id="div1">
<div id="div2"></div>
</div>
1
#div1 {
width: 400px;
height: 400px;
text-align: center;
border: 1px dotted #ccc;
display: table-cell;
vertical-align: middle;
}
#div2 {
display: inline-block;
width: 200px;
height: 200px;
background: #3BD9CD;
}
display: table-cell 单元格居中
2
#div1 {
width: 400px;
height: 400px;
text-align: center;
border: 1px dotted #ccc;
display: flex;
justify-content: center;
align-items: center;
}
#div2 {
width: 200px;
height: 200px;
background: #3BD9CD;
}
弹性布局, x, y轴居中
3
#div1 {
width: 400px;
height: 400px;
text-align: center;
border: 1px dotted #ccc;
position: relative;
}
#div2 {
width: 200px;
height: 200px;
background: #3BD9CD;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
这里的 transform 位置变换也可以用 margin 负值 50% 来位移.
4
#div1 {
width: 400px;
height: 400px;
text-align: center;
border: 1px dotted #ccc;
position: relative;
}
#div2 {
width: 200px;
height: 200px;
background: #3BD9CD;
position: absolute;
margin: auto;
top: 0;
left: 0;
right: 0;
bottom: 0;
}
需要设置宽高, 两侧自动填充.
版权属于:行川草庐 - 行川的网络日志
本文链接:https://www.xing-chuan.com/archives/23.html
本作品由行川采用知识共享署名-非商业性使用 4.0 国际许可协议进行许可