For example, I want a CSS selector for all div elements which have a CSS overflow:auto; property. Is it possible to have a selector of that kind?
3 Answers
CSS has evolved considerably since this question was asked and there's a (limited) way of achieving this with pure CSS: container style queries. Although it may not be helpful for the use case described in the comments, it could be useful for people looking to have a CSS selector based on a property (this question pops up as a top result on Google for searches like that).
Container style queries' notation is simple:
@container style(<style-condition-or-feature>) {
.myElement {
/* styles to apply when the queried style is true */
}
}
One of the limitations is that the queried styles must be at a container/ancestor level, not on the element itself. So you wouldn't be checking if the element has this or that style, but if an ancestor has an style:
section {
--border-color: red;
border: 1px dashed var(--border-color);
}
@container style(--border-color: red) {
div {
color: blue;
}
}
<section>
<div>
This text will be blue if an ancestor has a red border.
</div>
</section>
Another limitation, this one a bit more annoying, is that the queried styles must be a custom property (it will work with sizes but that would be container size query).
Notice that this is a current limitation. The CSS standard specifies that any feature property can be queried –and not exclusively custom properties–, but at the moment of writing this answer, browsers only support custom properties.
So in the future, something like this should work too:
section {
background: black;
}
@container style(background: black) {
div {
color: white;
}
}
<section>
<div>
If you see this text with white color over a black background,
your browser supports container style queries for any style
feature/declaration and not only for custom properties.
</div>
</section>
Container style queries were introduced in 2023 and are already supported by Chrome and Safari (but not by Firefox yet).
More information on container style queries:
divon the site having theoverflow:autoproperty at-once.$("div[overflow:auto]").niceScroll();rather than looking for all the div's in the site to find the ones which haveoverflow:autoproperty, and then callingniceScroll()on them.