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

2

12

I am using below css to align text middle and left when multi-line, but how to align text middle 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>
Phylissphyll answered 26/4, 2017 at 7:12 Comment(0)
E
22
  1. Wrap your text in an inline element like <span>.
  2. Make it inline-block and 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>
Endeavor answered 26/4, 2017 at 7:29 Comment(1)
When I searched this question on google, I was so unsure if this is possible. And here it is. Wow! I don't understand it unfortunately, but it works. ThanksSelfpreservation
T
-4

I'd 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");
   }
});

There may be better alternatives as this one is obviously not waterproof, but it should do the trick somewhat.

Tying answered 26/4, 2017 at 7:25 Comment(1)
length >= 50 is highly dependent on screen size, font-size, letter-spacing, font-characteristics, user's zoom settings, accessibility settings, and probably many other things. Lots of changes may break thisSelfpreservation

© 2022 - 2024 — McMap. All rights reserved.