A_user A_user - 6 months ago 18
HTML Question

Center text in div if single line else display ellipsis

I need to display max two lines of text in a div, and if text exceeds two lines then display ellipses at the end of two line text.

+------------------------+
| Some text for test and |
| Some text for test ... |
+------------------------+


Also if text is only single line then, I need to display that single line in middle of div, left aligned. (below example shows three lines and text, but it should be two lines :) ).

+------------------------+
| |
| Some text for test and |
| |
+------------------------+


Currently I am using below code:



.mainDiv {
font-size: 10px;
min-height: 10px;
max-height: 20px;
line-height: 10px;
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
text-overflow: ellipsis;
overflow: hidden;
}

<div class="mainDiv">
some text for test
</div>





Using above code it works well in case if text has two or more than two lines. But if text is single line then it is not displayed in center of div, it is displayed at the top.

Update

The problem is when we combine both:

1. Max 2 line ellipsis text in a div

2. Single row text in middle of div

functionality together.

Answer

You could probably wrap your mainDiv inside 2 divs with display: table-cell and display: table respectively. Then, vertical-align: middle on the cell.

You just need to set your outer-most div to your desired height.

Fiddle

.mainDiv {
  font-size: 14px;
  min-height: 10px;
  max-height: 20px;
  line-height: 10px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  text-overflow: ellipsis;
  overflow: hidden;
}

.container {
  display: table-cell;
  vertical-align: middle;
  border: 1px solid red;
  width: 100px;
  height: 100px;
}

.wrapper {
  display: table;
}
<div class="wrapper">
  <div class="container">
    <div class="mainDiv">
      text text text text text text text text text text text text text text text text text
    </div>
  </div>
</div>

<div class="wrapper">
  <div class="container">
    <div class="mainDiv">
      text text text
    </div>
  </div>
</div>

Comments