Skip to content

[css-nesting] How to resolve nested CSS with pseudo elements in the parent #7433

Closed

Description

@romainmenke

first reported here : csstools/postcss-plugins#510

relevant specification parts:

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

The nesting selector can be desugared by replacing it with the parent style rule’s selector, wrapped in an :is() selector. For example,

https://www.w3.org/TR/selectors-4/#matches-pseudo

Pseudo-elements cannot be represented by the matches-any pseudo-class; they are not valid within :is().

For this CSS :

.anything::before {
  @nest .something_else > & {
    color: black
  }
}

& should represent the matched element of the enclosing rule.
Which in this case is before.

This CSS :

  1. is invalid
  2. is valid but never matches
  3. matches .something_else > .anything::before
  4. matches .something_else.anything::before (or .something_else.anything :> before)

Also relevant :

Activity

  1. romainmenke commented on Jul 4, 2022

    @romainmenke
    MemberAuthor
  2. argyleink commented on Jul 7, 2022

    @argyleink

    I think you did the right thing reverting the change that tried to correct it for developers. I'm thinking wait/lean on devtools to help developers learn that :is() and :where() can't accept pseudo elements? add it to a style linter to watch out for? or the postcss plugin could notice nested :: and warn in the console?

    agree that this is a tough lesson in nesting, since the 1st lesson to be learned with is and where feels out of no where. heh, no:where()..

    i believe this is how the nested selectors can be rewritten.

    .anything {
      &::before {}
    
      @nest .something_else > &::before {
        color: black
      }
    }

    this makes me think we could add a warning to the spec that any nesting inside a ::before (or of same type) will produce an invalid selector per https://www.w3.org/TR/selectors-4/#matches-pseudo and have no matches.

  3. romainmenke commented on Jul 7, 2022

    @romainmenke
    MemberAuthor

    Adding a warning to the spec would be great! Anything that is invalid in :is is also invalid as a nesting ancestor (ancestor of the rule, not of the matched element)

    At the moment this is implied but not clear beyond any possible confusion.

    It's true that with nesting specifically stylesheet authors need to re-learn the feature and this is a painful process :/

    It was inspired by sass nesting but it is completely different from that.
    The first versions of the PostCSS plugin did something different altogether.

    So stylesheet authors have an intuitive sense of how the feature should work that doesn't match how it will eventually work in browsers.

    We already took some steps with the last major version of the PostCSS plugin but clearly more work is needed :)


    A (style)lint rule that can spot invalid nesting would be awesome and doesn't exist yet.
    This also gives faster feedback while typing.

  4. cdoublev commented on Jul 15, 2022

    @cdoublev
    Collaborator

    I am not sure I understand why ::before { &:hover {} } would be invalid. I do not claim it should. Even :is() not accepting pseudo-elements is not something already defined, I think. But I'm reading the note about the :is() desugaring trick as intended only for CSS processing tools authors.

  5. johannesodland commented on Oct 20, 2022

    @johannesodland
    Contributor

    Adding a warning to the spec would be great! Anything that is invalid in :is is also invalid as a nesting ancestor (ancestor of the rule, not of the matched element)

    As an author, I hope we don't drop nesting inside pseudo-elements just because it's not supported in :is() today.
    There are many use cases for nesting in pseudo-elements, and there will be more as more nested pseudo-elements are added.

    Nested conditional rules

    div::before {
      color: blue;
    
      @media (min-width: 480px) {
        color: red;
      }
    }

    **Nested user action pseudo classes **

    div::before {
      color: blue;
    
      &:hover {
        color: red;
      }
    }

    Nested pseudo-elements

    article::fist-letter {
      initial-letter: 3;
    
      &::prefix {
        font-size: 0.5em;
        vertical-align: top;
      }
    }

    It's not just that we are used to the existing feature. Making nesting inside pseudo-elements invalid will block many use cases, and will make it harder to teach and understand nesting. The specificity side-effects of using :is() will be surprising enough as it is.

    I understand making it invalid would make the feature easier to implement through :is() at the moment. I hope we can prioritise authors over ease of implementation, and perhaps look at extending support for nested pseudo-elements in :is(). Improved syntax for selecting pseudo-element children and descendants as described in 7346 would be great too.

  6. tabatkins commented on Oct 20, 2022

    @tabatkins
    Member

    The :is() desugaring, taken literally, just advice for tools, yeah. We don't actually produce an :is() internally. But the restrictions should exist in both places or neither.

  7. sesse commented on Oct 20, 2022

    @sesse
    Contributor

    FWIW, while the implementation in Blink doesn't literally produce an :is() internally (it couldn't, due to CSSOM demands), it produces something that is awfully close. It goes through the exact same path while matching, for instance. (See https://chromium-review.googlesource.com/c/chromium/src/+/3934883/16/third_party/blink/renderer/core/css/selector_checker.cc#1315 if you're interested)

  8. romainmenke commented on Oct 21, 2022

    @romainmenke
    MemberAuthor

    TL;DR;

    @supports selector(:is(::before)) and selector(& p) seems to be a valid way to check for support in the future if this remains true :

    But the restrictions should exist in both places or neither.


    I was looking at this from a feature detection perspective and I think a couple of things intersect here.

    • :is() is not forgiving in @supports, which was a recent change I think
    • you can not test for a nesting pattern with rules in @supports (e.g. @supports selector(::before { & {} }))

    Chrome 106:

    • @supports selector(:is(::before)) : true
    • @supports selector(& p) : false
    • @supports selector(:is(::before)) and selector(& p) : false

    Chrome 109:

    • @supports selector(:is(::before)) : false
    • @supports selector(& p) : true
    • @supports selector(:is(::before)) and selector(& p) : false
    <!DOCTYPE html>
    <html lang="en">
    <head>
    	<title>Document</title>
    	<style>
    		html {
    			& p { /* this is irrelevant, I just wanted to nest something */
    				color: green;
    			}
    		}
    
    		@supports selector(& p) {
    			p {
    				/* Version 109.0.5372.0 (Official Build) canary (arm64) */
    				/* Experimental platform features on */
    				text-decoration: underline solid green;
    			}
    		}
    
    		@supports selector(:is(::before)) {
    			p {
    				/* Version 106.0.5249.119 (Official Build) (arm64) */
    				text-decoration: underline wavy red;
    			}
    		}
    
    		@supports selector(:is(::before)) and selector(& p) {
    			p {
    				text-decoration: underline dotted purple;
    			}
    		}
    	</style>
    </head>
    <body>
    	<p>Hello!</p>
    </body>
    </html>
  9. LeaVerou commented on Oct 21, 2022

    @LeaVerou
    Member

    Conceptually, there is no reason to disallow this:

    .anything::before {
      .something_else > & {
        color: black
      }
    }

    So it would be unfortunate if we need to for what is basically an implementation detail. Perhaps we can just change how selectors get rewritten? Or maybe we could allow pseudo-elements in :is() and :where() for the cases where it makes sense?

  10. romainmenke commented on Oct 21, 2022

    @romainmenke
    MemberAuthor

    Perhaps we can just change how selectors get rewritten?

    Can you clarify?

  11. LeaVerou commented on Oct 21, 2022

    @LeaVerou
    Member

    Perhaps we can just change how selectors get rewritten?

    Can you clarify?

    E.g.

    .a, .b::before {
    	.c > & {
    		color: black
    	}
    }

    could be rewritten as:

    .c > .a,
    .c > .b::before {
    	color: black
    }
  12. romainmenke commented on Oct 21, 2022

    @romainmenke
    MemberAuthor

    Yes, but your comment hints at a larger change.

    An example where :is() is important :

    .parent .a, .other-parent .b::before {
    	.c > & {
    		color: black
    	}
    }

    currently matches like :

    .c > :is(.parent .a), .c > :is(.other-parent .b::before) {
    	color: black
    }

    Which is also why I agree with @tabatkins to keep these linked.
    Resolving this issue for both nesting and :is() at the same time is the least confusing.

  13. tabatkins commented on Oct 21, 2022

    @tabatkins
    Member

    "How selectors get rewritten" has only a few possibiltiies:

    1. Use :is().
    2. Fully expand the selectors, possibly resulting in a combinatorial explosion of selector length. (.a .b .c { .d .e & {...}} expands to, hm, 5-choose-2 selectors (10 total, in this case).
    3. Use something exactly like :is() except it allows more stuff.

    We're currently doing 1 (effectively). 2 is right out. 3 just raises the question of why we can't do that stuff in :is().

  14. johannesodland commented on Oct 21, 2022

    @johannesodland
    Contributor

    If I’m not mistaken, precompilers used to fully expand nested selectors. I’m not sure if it was a huge problem?

    If nested rules were fully expanded, we could rely on linters to warn authors of the expanded complexity. :is() can then be added selectively where needed.

    I think I might prefer this over nesting not working inside pseudo-elements and the unexpected specificity. This would also need linting to warn about invalid use.

  15. 14 remaining items

  16. tabatkins commented on Oct 27, 2022

    @tabatkins
    Member

    I now have an explicit restriction against & representing pseudo-elements in the spec, along with an issue noting that we'd like to fix it, but need to do so simultaneously for :is() since they rely on the same mechanisms.

  17. sesse commented on Oct 27, 2022

    @sesse
    Contributor

    Thanks!

  18. added
    Commenter Satisfied
    and removed on Oct 27, 2022
  19. matthew-dean commented on Apr 4, 2023

    @matthew-dean

    @tabatkins

    I know this is an old conversation, but just FWIW:

    They did not, precisely because this is a huge problem. Sass uses some heuristics to guess what subset of the possible selectors to actually emit. I presume other langs do so as well (or just have a combinatorial explosion in their output sometimes).

    Less essentially clamps the number of combinations you can have. Otherwise it's a terrible problem, and at least in Less threads / documentation, we warn authors that this is one of the dangers of over-nesting lists.

    Interestingly, I was going to open a suggestion in Less to, at some point, output :is() wrappers instead of combining selectors. Although this may not be necessary since it could just pass through nesting.

  20. matthew-dean commented on Apr 4, 2023

    @matthew-dean

    Interestingly, I was going to open a suggestion in Less to, at some point, output :is() wrappers instead of combining selectors.

    Hang on, pseudo-elements are not valid in :is()? 🤔 Why?

  21. tabatkins commented on Apr 6, 2023

    @tabatkins
    Member

    Because an element is never a pseudo-element (and you can't generically select a pseudo-element and then test its name in an :is()).

    That is, div:is(::before) is asking "is the div a ::before?" and that's never true (and similarly, ::before:is(::before) is either always or never true, depending on if the names match or not). What people expect it to mean is "change the subject of the selector to the div's ::before pseudo", but pseudo-classes can't change the subject; you need a combinator for that.

    Ultimately the problem is that early CSS screwed up the pseudo-element syntax, making it look like a pseudo-class (literally spelled it :before; the double-colon came later) rather than like a combinator+name. (There's some other issues to potentially fix that, tho I can't dig them up at the moment.)

  22. yisibl commented on Jun 20, 2024

    @yisibl
    Contributor

    This limitation is sure to confuse more and more authors, even developers of browser engines, see https://issues.chromium.org/issues/40278599

  23. LeaVerou commented on Jun 20, 2024

    @LeaVerou
    Member

    @yisibl can you please post this in 9492 which is the actual open issue for this?

  24. yisibl commented on Jun 20, 2024

    @yisibl
    Contributor

    @yisibl can you please post this in 9492 which is the actual open issue for this?

    No problem. Done

  25. rctneil commented on Mar 5, 2025

    @rctneil

    Just wanted to post that I have recently hit an issue which (i think) this is the culprit of. I'd love to see this scenario relaxed as it confused me for a good long time.

    Styles I was trying to use:

    ::part(form-control-label) {
        .filter-bar & {
            color: yellow;
        }
    }
    

    Discussion here: https://discord.com/channels/739437527907303535/1020332605599662181/1346201308448686191 and here: https://discord.com/channels/436251713830125568/1345141673478328532

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Closed Accepted by Editor DiscretionCommenter Satisfiedcss-nesting-1

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions

      Sponsor
      SponsoredKunjungi sekarang
      Promo