skip to Main Content

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


  1. Chosen as BEST ANSWER

    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.


  2. The spec explicitly tells that:

    The nesting selector cannot represent pseudo-elements (identical to the behavior of the :is() pseudo-class).

    https://www.w3.org/TR/css-nesting-1/#nest-selector

    I.e. the same way like you cannot target ::before with `:is():

    *:is(::before){ /* never matches anything */ } 
    *:has(::before){ /* neither this */ } 
    

    the same way you cannot refer to ::before with &

    *::before { & { /* never matches */ } }
    

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search