Media queries can be used inside selectors, but they seem to be ignored inside pseudo elements in plain css.
Example:
div.container {
color: red;
&::before {
display: inline-block;
content: "shouldn't display.";
@media screen and (min-width: 1px) {
content: "should display?";
}
}
@media screen and (min-width: 1px) {
&::before {
content: "displays?";
}
}
}
div.no-nest::before {
content: "shouldn't display.";
@media screen and (min-width: 1px) {
content: "should display";
}
}
div.no-pseudo {
span.hide {
@media screen and (min-width: 1px) {
display: none;
}
}
}
<div class="container">
-- content here.
</div>
<div class="no-nest">
-- content without nested css
</div>
<div class="no-pseudo">
<span class="hide">shouldn't display</span>
<span class="show">should display</span>
-- content without pseudo
</div>
https://jsfiddle.net/jwe6kcda/1/
Is this correct? Does the spec say this is not possible? This usually works in SCSS and I’m surprised this didn’t carry over when the specification for nested css was made, specially since it works for any .selector
.
2
Answers
The spec for css nesting says that "In addition to nested style rules, this specification allows nested group rules inside of style rules: any at-rule whose body contains style rules can be nested inside of a style rule as well."
Then here, the definition of "style rule" states: "A style rule is a qualified rule that associates a selector list with a list of property declarations".
Selector List: "A list of simple/compound/complex selectors is a comma-separated list of simple, compound, or complex selectors."
Which has an issue, noted in the spec "Pseudo-elements aren’t handled here, and should be."
So yeah, the way I see it, common sense says it should work, but there's an issue with the spec itself.
thanks to @heretic-monkey for the link to the spec.
The spec explicitly tells that:
— https://www.w3.org/TR/css-nesting-1/#nest-selector
I.e. the same way like you cannot target
::before
with `:is():the same way you cannot refer to
::before
with&
Spec refers to discussion mentioning it might be relaxed in the future, but will demand substantial changes in related mechanisms. Not sure if it is likely to happen.