【问题标题】:How to make single-line text center align while multi-line left align?如何在多行左对齐时使单行文本居中对齐?
【发布时间】:2017-04-26 16:03:09
【问题描述】:
我在多行时使用下面的css将文本居中对齐,但是如何在一行时将文本居中对齐?
.my-text {
border: 1px solid black;
width: 400px;
height: 160px;
vertical-align: middle;
display: table-cell;
overflow: hidden;
line-height: 20px;
padding: 20px;
}
<div class="my-text">
carpe diem
</div>
<div class="my-text">
carpe diem carpe diem carpe diem carpe diem carpe diem carpe diem carpe diem carpe diem carpe diem carpe diem carpe diem carpe diem carpe diem
</div>
【问题讨论】:
标签:
html
css
alignment
text-align
【解决方案1】:
- 将您的文本包装在像
<span> 这样的内联元素中。
- 将其设为
inline-block,并将其文本对齐方式设置为left。
.my-text {
border: 1px solid black;
width: 400px;
height: 160px;
vertical-align: middle;
display: table-cell;
overflow: hidden;
line-height: 20px;
text-align: center;
padding: 10px;
}
.my-text span {
display: inline-block;
vertical-align: top;
text-align: left;
}
<div class="my-text">
<span>carpe diem</span>
</div>
<div class="my-text">
<span>carpe diem carpe diem carpe diem carpe diem carpe diem carpe diem carpe diem carpe diem carpe diem carpe diem carpe diem carpe diem carpe diem</span>
</div>
【解决方案2】:
我建议使用 JQuery 解决方案:
$(".my-text").keypress(function() {
if($(this).val().length >= 50) {
$(this).css("text-align", "left");
}
else {
$(this).css("text-align", "center");
}
});
可能有更好的替代品,因为这个显然不防水,但它应该可以起到一定的作用。