CSS-only detection of text overflows in HTML?
Asked Answered
B

3

28

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!

Blurt answered 17/9, 2013 at 7:50 Comment(3)
i don't think its possible only with css, but I could be wrong.Yestreen
Javascript examples: #7669136 (with a fiddle), #7139272, #11773529Blurt
I've created a fiddle which is a cleaner example of the fiddle (jsbin actually) indicated above which gets a bit more detailed on the JavaScript imlementations: jsbin.com/apEHAdI/5/edit?html,css,js,outputBlurt
D
12

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.

Devaluation answered 17/9, 2013 at 7:59 Comment(0)
B
10

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, …

Bruyn answered 11/2, 2020 at 7:45 Comment(1)
These kinds of gotchas can already happen, e.g. an element, when hovered, moves from underneath the user's mouse which makes it not hovered so it moves back, etc. One way to restrict these paradoxes is to only allow children of the targeted element to be modified via CSS.Altagraciaaltaic
F
0

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.

F answered 30/9, 2020 at 16:52 Comment(1)
There's a few more requirement for this to work as well, stated here: #17779793Kirkcudbright

© 2022 - 2024 — McMap. All rights reserved.