原文链接:10种水平垂直居中对齐方式(史上最全)
在子元素知道宽高的条件下:
<div class="parent" style="border: 1px solid #000;width:400px;height:400px">
<div class="child" style="background: blue;width:200px;height:200px">
</div>
</div>
1.absolute + top + left + 负margin
.parent {
position: relative;
}
.child {
position: absolute;
top: 50%;
left: 50%;
margin-top: -100px;
margin-left: -100px;
}
2.absolute + top + left + bottom + right + margin:auto
.parent {
position: relative;
}
.child {
position: absolute;
margin: auto;
top: 0;
right: 0;
bottom: 0;
left: 0;
}
3.absolute + calc (原理同方法1,兼容IE10+)
.parent {
position: relative;
}
.child {
position: absolute;
top: calc(50% - 100px);
left: calc(50% - 100px);
}
在子元素不定宽高的条件下,大小由内容决定:
<div class="parent" style="border: 1px solid #000;width:400px;height:400px">
<div class="child" style="background: blue;">
我是文本,我是文本,我是文本,我是文本,我是文本
</div>
</div>
1.absolute + transform(IE9+)
.parent {
position: relative;
}
.child {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
2.lineheight
.parent {
line-height: 400px;
text-align: center;
font-size: 0;
}
.child {
font-size: 16px;
display: inline-block;
vertical-align: middle;
line-height: initial;
text-align: left; /* 修正文字 */
}
3.flex(注意浏览器兼容:IE11+,chrome 55+)
//父元素flex布局加子元素自适应margin
.parent {
display: -webkit-box;
display: -webkit-flex;
display: -moz-flex;
display: -ms-flexbox;
display: flex;
}
.children {
margin: auto;
}
//或者直接在父元素种使用flex属性
.parent {
display: flex;
align-items:center;
justify-content: center;
}
4.table(代码冗余,不推荐)
将内容置于table单元格中,table单元格自带垂直居中属性,添加水平居中样式text-align: center即可
5.css-table
.parent {
display: table-cell;
text-align: center;
vertical-align: middle;
}
.child {
display: inline-block;
}
6.write-mode(代码冗余,不推荐)
//父元素需要多加一个inner层
<div class="parent" style="border: 1px solid #000;width:400px;height:400px">
<div class="parent_inner">
<div class="child" style="background: blue;">
我是文本,我是文本,我是文本,我是文本,我是文本
</div>
</div>
</div>
<style>
.parent {
writing-mode: vertical-lr;
text-align: center;
}
.parent_inner {
writing-mode: horizontal-tb;
display: inline-block;
text-align: center;
width: 100%;
}
.child {
display: inline-block;
margin: auto;
text-align: left;
}
</style>
7.grid
.parent {
display: grid;
}
.child {
align-self: center;
justify-self: center;
}
网友评论