Overflow/scrollbar detection using modern CSS
Do you want to detect if an element is having an overflow or if it's scrollable? It's possible with scroll-driven animation! You can also store this information within a variable at :root
level and do whatever you want (like styling any elements on the page)
:root {
timeline-scope: --scroll;
animation: --scroll forwards;
animation-timeline: --scroll;
container-name: --scroll;
}
.box { /* the concerned element */
overflow: auto; /* or hidden */
scroll-timeline: --scroll;
}
@keyframes --scroll {
0%,to{--scroll: 1;}
}
@container --scroll style(--scroll: 1) {
/* The CSS when .box is overflowing
you can target any element on the page!
*/
}
/* Yes you can use --scroll everywhere! */
Resize the .box
element in the demo below and see the magic! (chrome only for now)
See the Pen Overflow detection using only CSS by Temani Afif (@t_afif) on CodePen.
The use of style query is not mandatory and you can have a simpler version if you want to target the concerned element.
.box {
overflow: auto; /* or hidden */
animation: scrolling forwards;
animation-timeline: scroll(self);
}
@keyframes scrolling {
0%,to{
/* the CSS applied to .box when it has overflow */
}
}
Or a child element
.box {
overflow: auto; /* or hidden */
}
.box .child {
animation: scrolling forwards;
animation-timeline: scroll(); /* it will consider the ancestor having overflow: auto/hidden */
}
@keyframes scrolling {
0%,to{
/* the CSS applied to .child when .box has overflow */
}
}
See the Pen Overflow detection using only CSS (simple version) by Temani Afif (@t_afif) on CodePen.