如果发生换行,如何使文本垂直居中
How to center text vertically if line break occurs
基本上我的问题是关于容器内的文本。当屏幕尺寸变小时,它会进入下一行。那时,它不再垂直居中,因为出现了新的一行。
如何让它保持垂直居中?
<div class="low">
<h4 class="title"> Text to be centered. </h4>
</div>
我通常会为每个换行符调整填充,但这既麻烦又耗时。一定有更好的方法。
您可以将 text-align
属性 设置为 center
。但是,如果容器的宽度使其内容不能居中对齐,它将失败。
.low {
width: 50px;
}
.title {
text-align: center;
}
<div class="low">
<h4 class="title"> Text to be centered. </h4>
</div>
试试这个
div{
display:table;
background-color:#ccc;
height:50px;
}
h4{
display:table-cell;
vertical-align:middle;
}
<div class="low">
<h4 class="title"> Text to be centered. </h4>
</div>
你必须使用 display: flex;
使其垂直居中:
.low {
display: flex;
justify-content: center;
flex-direction: column;
text-align: center;
}
基本上我的问题是关于容器内的文本。当屏幕尺寸变小时,它会进入下一行。那时,它不再垂直居中,因为出现了新的一行。
如何让它保持垂直居中?
<div class="low">
<h4 class="title"> Text to be centered. </h4>
</div>
我通常会为每个换行符调整填充,但这既麻烦又耗时。一定有更好的方法。
您可以将 text-align
属性 设置为 center
。但是,如果容器的宽度使其内容不能居中对齐,它将失败。
.low {
width: 50px;
}
.title {
text-align: center;
}
<div class="low">
<h4 class="title"> Text to be centered. </h4>
</div>
试试这个
div{
display:table;
background-color:#ccc;
height:50px;
}
h4{
display:table-cell;
vertical-align:middle;
}
<div class="low">
<h4 class="title"> Text to be centered. </h4>
</div>
你必须使用 display: flex;
使其垂直居中:
.low {
display: flex;
justify-content: center;
flex-direction: column;
text-align: center;
}