目录
display:table-cell、vertical-align:middle属性详解
HTML文本
<div class="parent">
<div class="child"></div>
</div>
显示效果
方式1
设置position:absolute,top、bottom、right、left=0,margin:auto。
通过设置相对定位4个方向为0并将margin设置为auto使其自动平分上下左右的间距。
.parent {
width: 300px;
height: 300px;
background-color: #ddd;
position:relative;
}
.child {
position: absolute;
background-color:red;
/*竖直方向居中*/
top: 0;
bottom: 0;
/*水平方向居中*/
left: 0;
right:0;
margin: auto;
/*行内文本居中*/
width: 100px;
height: 100px;
line-height: 100px;
}
方式2(2种)
position:absolute ,top=left=50%-1/2h(w)
使用相对父集定位,因为子元素是以左上角顶点为定位点所以要减去自身1/2的宽高,我们可以通过calc计算也可以通过transform属性去平移。
.parent {
width: 300px;
height: 300px;
background-color: #ddd;
position:relative;
}
.child {
position: absolute;
/*方法一*/
left: calc(50% - 50px);
top: calc(50% - 50px);
/*方法二*/
/* top: 50%;
left: 50%;
transform: translate(-50%,-50%); */
background-color:red;
width: 100px;
height: 100px;
line-height: 100px;
}
注意:clac函数可以使用百分比和像素计算,但是中间的符号2边要带空格,不然无法生效。
方式3
使用display:flex属性
设置主轴和副轴方向对齐方式为居中。详细解释见下面链接:
display:flex属性详解
.parent {
width: 300px;
height: 300px;
background-color: #ddd;
display: flex;
align-items: center;
justify-content: center;
}
.child {
background-color:red;
width: 100px;
height: 100px;
line-height: 100px;
}
方式4
使用display:grid属性
不划分单元格,相当于大容器parent为一个大的单元格,设置单元格主轴和副轴方向对齐方式为居中。详细解释见下面链接:
display:grid属性详解
.parent {
width: 300px;
height: 300px;
background-color: #ddd;
display: grid;
align-items: center;
justify-content: center;
}
.child {
background-color:red;
width: 100px;
height: 100px;
line-height: 100px;
}
方式5
使用display:table-cell属性
.parent {
width: 300px;
height: 300px;
background-color: #ddd;
/*display: table;*/
display: table-cell;
vertical-align: middle;
text-align: center;
}
.child {
display: inline-block;
/* 水平居中对齐 */
background-color:red;
/* margin: 0 auto; */
width: 100px;
height: 100px;
line-height: 100px;
}
注意:display:inline-block;和margin: 0 auto;只用一个即可。
display:table-cell;vertical-align:middle;text-align: center;属性含义见下面链接
display:table-cell、vertical-align:middle属性详解
CSS中vertical-align和text-align属性详解(使用场景、举例、注意点)、display:table-cell使用详解(基础介绍和使用例子)。_AIWWY的博客-优快云博客