Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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>
like image 719
licaomeng Avatar asked Apr 26 '17 07:04

licaomeng


People also ask

How do I center only one line in HTML?

Using the <center></center> tags One way to center text or put it in the middle of the page is to enclose it within <center></center> tags. Inserting this text within HTML code would yield the following result: Center this text!


1 Answers

  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>
like image 198
Mohammad Usman Avatar answered Nov 15 '22 22:11

Mohammad Usman