一、相对定位和负边距
我们可以使用相对定位和负边距的方法实现文字的垂直居中。具体操作是设置文字所在容器为相对定位,再在文字元素中设置top和margin-top两个属性,其中top的值为50%,margin-top的值为文字高度的一半乘以-1。
.container{
position:relative;
}
.text{
position:absolute;
top:50%;
margin-top:-10px;
}
注意,这种方法适用于文字高度固定的情况下,如果高度不定,需要使用JavaScript获取高度动态计算margin-top的值。
二、使用表格布局
使用表格布局也是一种实现文字垂直居中的方法,我们可以设置容器为table,文字元素为table-cell,再在文字元素中使用vertical-align:middle属性即可。这种方法适用于支持表格布局的各种浏览器。
.container{
display:table;
}
.text{
display:table-cell;
vertical-align:middle;
}
三、使用Flex布局
Flex布局是一种很流行的布局方式,也可以用来实现文字的垂直居中。我们可以设置容器为display:flex,并在文字元素中设置align-items:center和justify-content:center两个属性。
.container{
display:flex;
align-items:center;
justify-content:center;
}
.text{
/*无需设置*/
}
四、使用Grid布局
Grid布局是一种比较新的布局方式,在实现文字垂直居中方面也很方便。我们可以设置容器为display:grid,再在文字元素中使用align-self:center和justify-self:center两个属性。
.container{
display:grid;
}
.text{
align-self:center;
justify-self:center;
}
五、line-height方法
通过设置line-height属性也可以实现文字垂直居中。我们可以将line-height的值设置为容器高度的值,在文字元素中使用display:inline-block来使得line-height属性生效。
.container{
height:20px;
}
.text{
display:inline-block;
line-height:20px;
}