How to do text alignment in single line text while multiline left alignment?

I use below css to align text in the middle and left when multi-line, but how to align text in the center and center when one line?

.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>
Run codeHide result
+4
source share
2 answers
  • Wrap the text with an inline element, for example <span>.
  • Make it inline-blockand set its text alignment to 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>
Run codeHide result
+7
source

I would recommend using a jQuery solution:

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

, , , , .

0

Source: https://habr.com/ru/post/1675676/


All Articles