Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS *only* detection of text overflows in HTML?

I've seen suggestions on using JavaScript for detecting and acting on text that overflows an HTML element. But it's 2013, so I was wondering if maybe the CSS spec had a way to detect overflows itself.

In other words if I have a fixed size div:

<div class="smart-warning" style="width:200px; height:20px; overflow:hidden">
This is my very long text that would overflow the box.
</div>

I'd like to have a style that would do something if the text overflowed such as:

<style>
.smart-warning {
  border:1px solid black
}
.smart-warning:overflowing {
  border:1px solid red
}
</style>

It seems like we'd be really close to having something like this in CSS but pouring over the specifications is not my game.

If it doesn't exist, do you think it would be useful?

Thanks!

like image 401
iJames Avatar asked Sep 17 '13 07:09

iJames


People also ask

How do you know if text is overflowing CSS?

Check its style. overflow property, if it is 'visible' then the element is hidden. Also, check if its clientWidth is less then scrollWidth or clientHeight is less then scrollHeight then the element is overflowed.


3 Answers

I am not aware of any part of the CSS spec, where this would be possible. Selectors Level 4 supports a lot of new pseudo-classes (and quite some useful ones for checking states on input elements) but none of these are actually able to check conditions like if a box is overflowing. You still have to do this via Javascript.

like image 102
Christoph Avatar answered Oct 02 '22 10:10

Christoph


The reason why this will never be possible with CSS is because that would lead to paradoxes.

Consider the following:

.box {
    height: 100px;
}

.box:overflowing {
    height: 200px;
}

.content {
    height: 150px;
}

Now if the box is overflowing, it gets a height of 200px, which means it is no longer overflowing, which means it gets a height of 100px, wich means it is now overflowing, …

like image 45
ThomasR Avatar answered Oct 01 '22 10:10

ThomasR


If your div will be a single line, you could add:

    text-overflow: ellipsis;
    white-space: nowrap;

This ellipsis property adds "..." to the end of whatever fits inside your width constraints (adding a visual indicator to your overflowing divs.) As far as I know, it only works in combination with the nowrap property though.

like image 41
user3044020 Avatar answered Oct 04 '22 10:10

user3044020