Reputation: 9010
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?
Upvotes: 17
Views: 5885
Reputation: 29645
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:
Upvotes: 1
Reputation: 49200
Note that style="overflow:auto;"
will match divs which has exact that CSS (string). If you want to select divs that contains overflow:auto
along with some other css, you can use *
selector.
div[style*="overflow:auto;"]{
background-color: #f00;
}
Upvotes: 7
Reputation: 85545
No. There's no way to do this with css. You need to use scripting language.
But if you have defined style in your html like the following then this would be possible like:
div[style="overflow:auto;"]{
background-color: #f00;
}
<div style="overflow:auto;">overflow is auto</div>
Upvotes: 9