Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS selector for truncated text

If I have a truncated label is there any way to tell if the text was too long? This would be helpful for conditionally adding additional styling for clipped text.

.truncate {
  width: 250px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

Here is what I would like to be able to do.

.truncate:truncated {
  color: red;
}
like image 709
Swazimodo Avatar asked Aug 25 '26 13:08

Swazimodo


1 Answers

If you don't mind using a little JavaScript, the solution is trivial.
Not sure if there is a non-JavaScript solution.

var divs = document.querySelectorAll('.truncate');
for (var i = 0; i < divs.length; ++i)
  if (divs[i].scrollWidth > divs[i].clientWidth)
    divs[i].classList.add('truncated');
.truncate {
  width: 250px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.truncate.truncated { /* note the dot here instead of a colon */
  color: red;
}
<div class="truncate">
  This is the content
</div>
<div class="truncate">
  This is the content that is far longer than the container
</div>
like image 138
Mr Lister Avatar answered Aug 27 '26 02:08

Mr Lister



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!