如何使单行文本居中对齐而多行文本左对齐?

How to make single-line text center align while multi-line left align?

下面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>

我建议使用 JQuery 解决方案:

$(".my-text").keypress(function() {
   if($(this).val().length >= 50) {
      $(this).css("text-align", "left");
   }
   else {
     $(this).css("text-align", "center");
   }
});

可能有更好的替代品,因为这个显然不防水,但它应该能起到一定的作用。

  1. 将您的文本包裹在一个内联元素中,例如 <span>
  2. 将其设为 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>