Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[css-nesting] request to pick up the css-nesting proposal #2701

Closed
jonathantneal opened this issue May 24, 2018 · 67 comments
Closed

[css-nesting] request to pick up the css-nesting proposal #2701

jonathantneal opened this issue May 24, 2018 · 67 comments
Assignees
Labels
css-nesting-1 Current Work

Comments

@jonathantneal
Copy link
Contributor

https://tabatkins.github.io/specs/css-nesting/

The CSS Nesting module introduces the ability to nest one style rule inside another, with the selector of the child rule relative to the selector of the parent rule. This increases the modularity and maintainability of CSS stylesheets.

This is a followup to #998, and a long-time request from developers.

Has this been discussed in an agenda yet? If not, could this please be added to a future agenda?

Tweets lifted from @chriscoyier, @LeaVerou, @auchenberg, and @SaraSoueidan. Specification by @tabatkins.

@jescalan
Copy link

Couldn't be more in favor of this. Every developer uses css nesting and has forever through sass/less/stylus/postcss/etc, and it seems like the spec is in a solid place. Not having to pre-compile nesting anymore would be fantastic.

@LeaVerou
Copy link
Member

LeaVerou commented May 25, 2018

Yes please.

I wonder if this could also solve developers' requests for scoping. Two birds with one stone. I.e. instead of having nesting as merely syntactic sugar for the equivalent selectors, making it an alternative to preprocessors, make these rules have higher priority than non-scoped rules.

To clarify with an example, given the following CSS:

#foo p { color: red }

.bar {
  & p { color: green }
}

and the following HTML:

<div id="foo">
  <div class="bar">
    <p>foo</p>
  </div>
</div>

The paragraph would be green.

I know that we are dead set against introducing any new specificity rules, but it seems that scoping is such a huge problem that developers are avoiding the cascade altogether (see also CSS in JS which apparently half of devs use now?), We need to give them tools to avoid these problems, and it doesn't look like minor changes will do it. @tabatkins seemed to understand the problem well in a series of recent tweets, perhaps he can elaborate here too.

@fantasai
Copy link
Collaborator

fantasai commented May 25, 2018

@LeaVerou See https://www.w3.org/TR/2014/WD-css-scoping-1-20140403/#scope-atrule ? I think if it's affecting the cascade in such a way, it should be more explicit. Nesting has traditionally been just syntactic sugar.

@bradkemper
Copy link
Contributor

+1 on nesting, and also +1 on being explicit with an @scope.

For Lea’s example, I would be surprised if the specificity was not equivalent to .bar p.

@LeaVerou
Copy link
Member

Agreed, haven't seen the @scope rule!

@anjia
Copy link

anjia commented May 29, 2018

Clap clap. Look forward to using css-nesting in browsers directly without any pre-compiling.

Even though css-nesting looks like a syntactic sugar, it means the enhancement of coding efficiency and code maintainability for CSS, you know, which is what developers are gladly pursuing for. And sometimes, writing style could affect people's thinking processes.

And @scope is also a very useful feature, it could allow authors to use short classnames and selectors without worrying about unexpected cascading, or styles interaction among different UI components on the same page.

@fantasai
Copy link
Collaborator

@scope isn't syntactic sugar though. It adds another dimension to the cascade, more significant than specificity but less significant than origin/importance. See https://www.w3.org/TR/2016/CR-css-cascade-3-20160519/#cascading which defines how scoping affects the cascade.

@anjia
Copy link

anjia commented May 30, 2018

Even though it seems like just a syntactic sugar, it means the enhancement of ...

Oh, the pronoun it above refers to nesting. Eh, it's really easy to result in ambiguity, I'm going to update my comment to clarify this.

@fantasai thanks for your details and relevant link :)

@tobireif
Copy link

Please also see the existing ticket #998 .

@tobireif
Copy link

I also want nesting, it'd be a useful feature.

Regarding https://tabatkins.github.io/specs/css-nesting/ :

I'd prefer a syntax like that of Sass

https://sass-lang.com/guide#topic-3

where it's not necessary to add the ampersand.

In Sass, the ampersand is available (but not required - that's what I want).

https://sass-lang.com/documentation/file.SASS_REFERENCE.html#parent-selector

One of their examples:
(plus my comments)

#main {
  color: black;
  /* ampersand not required: */
  a {
    font-weight: bold;
    /* ampersand can be used when necessary: */
    &:hover { color: red; }
  }
}

is equivalent to this:
(the second part of their example) (their formatting)

#main {
  color: black; }
  #main a {
    font-weight: bold; }
    #main a:hover {
      color: red; }

@tabatkins
Copy link
Member

My spec explains why that's not a viable possibility. (Browsers don't want unbounded lookahead in their CSS parsers.)

It also privileges the descendant combinator, which isn't ideal.

@tobireif
Copy link

tobireif commented Jun 1, 2018

that's not a viable possibility.

If I understand you correctly it is a viable/possible option but it would require unbounded lookahead in CSS parsers.

From your draft:

"this drawback is generally considered unacceptable among popular implementations of CSS."

Are there sources for this?

Is it a performance issue?

It also privileges the descendant combinator, which isn't ideal.

Can you elaborate? Thanks in advance!

As for most feature wishes: The main objective (speaking for myself) is to get the feature, the rest is just details.

I'd strongly prefer not being required to prepend an ampersand to every single nested rule, and I hope that spec writers and implementers find a way to avoid that (perhaps it could be prototyped and tested and perhaps the perf impact is not really noticeable), but I'll sure take the feature even with that tedious requirement.

@tabatkins
Copy link
Member

Are there sources for this?

The sources are that this group is full of browser developers, and they've expressed that exact sentiment.

Is it a performance issue?

Potentially, but it also just rules out certain nice classes of parsers. Bounded lookahead is very convenient and has well-known performance characteristics.

@tobireif
Copy link

tobireif commented Jun 1, 2018

it also just rules out certain nice classes of parsers

The syntax should be nice for its users. I don't think I should have to care about whether the parser is nice or not 😀

Bounded lookahead is very convenient

I think that the syntax should be very convenient for its users / for web developers.

The potential performance hit should get verified before the API makes amends - the actual perf hit in real-world stylesheets might be negligible.

@jonathantneal
Copy link
Contributor Author

@tobireif, have you experimented with nesting in a manner that reflects the current spec? While it isn’t 1:1 like Sass, I eventually preferred it because it was easy to scan and explicit without adding many characters (typically only one, &):

#main {
  color: black;

  & a {
    font-weight: bold;
  }

  @nest main > & {
    color: navy;
  }
}

You can experiment with it here: https://preset-env.cssdb.org/playground (I hope everyone will forgive my sharing that link, as I try hard not to seem like a salesperson.)

@LeaVerou
Copy link
Member

LeaVerou commented Jun 1, 2018

@tobireif I sympathize with the usability concerns you are expressing (especially since usability is my research area). However, in this group we tend to take implementor concerns very seriously into account. Specs that are not implementable are just pointless fantasy documents. If you want to argue that the ampersand should not be required, a technical argument about how to implement that within bounded lookahead would be more effective than a philosophical argument. Also do note that the current spec does not prevent making the ampersand optional in the future, if a good way to implement that performantly comes up.

@LeaVerou
Copy link
Member

LeaVerou commented Jun 1, 2018

@tabatkins Can we allow relative selectors to this? That would reduce the characters needed, and descendants could be specified as >> foo. Since no properties start with combinators, that should not interfere with bounded lookahead.

@tabatkins
Copy link
Member

That's theoretically possible, sure; no grammar problems with it. But it means that now there's 3 nesting forms: if you're nesting with a combinator, use it directly (but you can use & if you want); if you're nesting by just adding more selectors, you have to use &; if you're doing anything more complicated, you have to use @nest.

The current rules are simpler - when you nest, you need to produce a full new selector with a & in it, referring to whatever's matched by the parent selector; if the & isn't the very first thing, you have to use @nest. The requirement is straightforward, and the condition for changing to @nest is visually obvious. I think this simplicity is pretty valuable!

@LeaVerou
Copy link
Member

LeaVerou commented Jun 5, 2018

Alternatively, the only ambiguous case is when the selector starts with an element selector, right? If it starts with an id, class, pseudo-class, or pseudo-element, we know immediately.
What if the ampersand was only required in that case?
This will simplify a ton of cases. It has the drawback if being a little less consistent but then again, so was requiring whitespace around + and - in calc(), but we did that. 😁

@FremyCompany
Copy link
Contributor

I don't see strong reason to change the current spec.

@fantasai
Copy link
Collaborator

fantasai commented Jun 6, 2018

I would like to see a discussion from the authoring perspective on Nesting vs Scoping and whether one is better or both are needed or what.

It's clear to me that people don't like repeating selectors, but it's less clear to me whether the desire for nesting is related to manipulating the cascade as well (which is poorly done via nesting, and better done via scoping) or the current specificity effects are exactly what's desired and only a syntactic manipulation is wanted.

As a review: Nesting merely adds up the specificities of the selectors which are chained together. (It's just a syntactic manipulation, which can be done with a preprocessor.) With Scoping, “The specificity of selectors inside the @scope rule is calculated locally: the selector specifying the scoping element is ignored. However, because scoped styles override non-scoped styles, style rules inside the @scope will override rules outside of it.” (If multiple @scopeed rules apply to an element, the rule with the deepest scoping element wins. See details in Cascade.)

@css-meeting-bot
Copy link
Member

The Working Group just discussed request to pick up the css-nesting proposal.

The full IRC log of that discussion <dael> Topic: request to pick up the css-nesting proposal
<dael> github: https://github.com//issues/2701
<dael> TabAtkins: The proposal is relatively simple. Wrote a spec a few years back. I'm fine but it's a syntax nicity where we didn't get it past hte community. If that's changed we can move it forward
<dael> fantasai: leaverou comment talks about wanting different specificity handling or the cascade. That's not syntactic only where you can do it wwith a preprocessor. There was @scope proposal before. I don't know if that's wanted still. I want to see more of that discussed. Do we want to effect cascade, if yes how. If we do this we should find out what's desired.
<dael> TabAtkins: I strongly believe nothing new on specificity. b/c nesting is in every preprocessor in existance doing so would be a major behavior change.
<dael> fantasai: No, not with same syntax.
<dael> TabAtkins: Second reason is it wouldn't be same as @Scoped and it would produce thigns that some ways resembe but some way don't. @Scoped wasn't popular and doesn't do what people want for scoping.
<dael> leaverou: I agree with TabAtkins, people are used to using nesting for preprocessors. I dsiagree with my earlier comment. I think scoping is useful, Not sure usability of scoping prop. It shouldn't hold nesting back.
<dael> TabAtkins: Happy to have that separate.
<dael> astearns: Objections to working on a purely syntactic nesting proposal
<dael> astearns: One concern is if you can do it in a preprocessor why do it, but even the preprocessor authors are asking us to do it.
<dael> chris: preprocessor expands to a ton of stuff and we don't want that expansion
<gsnedders> It's one less reason to use a preprocessor, IMO.
<gsnedders> And that's a good thing.
<fantasai> s/wanted still/wanted or something different/
<dael> astearns: Maybe an issue that we want to avoid the exposion of conbinations that can happens
<bkardell_> better for authors, better for network, very slightly worse for processing perf maybe?
<dael> florian: For OM representation yes, but effect that's unavoidable
<dael> TabAtkins: CSS style rules gain a child. OM doesn't explode
<dael> chris: That's a big advantage
<dael> leaverou: Huge advantage you can fo hover or focus styles on a one off
<dael> TabAtkins: Originally a proposal to do rules inside style attribute and this doens't have that. You need only one token of look ahead.
<dael> astearns: Obj to resolving we want to move forward with pure syntactic nesting?
<dael> TabAtkins: And I want the impl to say if they actually don't want it.
<tantek_> I'm too confused to comment on this last minute on the call
<dael> dbaron: If you're discussing changing what's in proposal it would be good to have that written to share around
<dael> TabAtkins: Entire proposal is linked in the issue to a spec on my personal github. It's laid out with no odd changes
<dael> TabAtkins: We can go to next week
<dael> astearns: We're over time. I don't hear obj. I think we are going to move forward, but let's give people time and we'll come back.
<dbaron> I think for Gecko implementation it's probably worth asking heycam and emilio rather than me.

@astearns astearns removed the Agenda+ label Jun 7, 2018
@AmeliaBR
Copy link
Contributor

AmeliaBR commented Jun 7, 2018

Happy to see this moving forward into deeper discussion!

But as I review @tabatkins draft, here are some issues that jump out to me:

  1. Based on the recent decision to change how :matches() specificity works ([selectors-4] reconsider specificity rule for :matches() #1027), we would need to decide whether a, b { & c {prop:val}} expands as a c, b c {prop: val} or as :matches(a,b) c {prop: val} (which could for some values of a and b result in different specificity than how it works with pre-processors). Then, all examples would need to be updated to consistently use one expansion or the other.

  2. It's worth calling out that Tab's proposed & is less powerful than the SCSS &. I understand the parsing reasons for the limitations, but it means you won't be able to blindly convert all SCSS nesting code to plain nested CSS.

    Some examples of SCSS features which wouldn't be supported in the proposal (P.S. Useful reference to SCSS nesting, for comparison):

    • Omitting the & for parent-child relationships.

    • Allowing the & anywhere in the selector, like:

      :link { .container & {/* link styles inside that container */} }
      

      In Tab's proposal, you could create this functionality with an explicit @nest rule:

      :link { @nest .container & {/* link styles inside that container */} }
      
    • Extending a single selector token, for example to create BEM-style modified classes like:

      .block { &__elem { &--modifier { /*styles*/ } } }
      

      which in SCSS compiles to a single class:

      .block__elem--modifier { /* styles */ }
      

      I don't think this would be supported at all in Tab's proposal, since it requires merging tokens after parsing.

  3. This looks like something that could be an implementation issue and/or a source of authoring issues:

    The relative ordering of nested style rules and other declarations is important; it’s possible for a given style rule and a nested style rule within it to match the same element, and if the specificity of the two rules is otherwise equivalent, the relative order in the stylesheet of the applicable declarations determines which declaration "wins" the cascade.

    CSS in many places requires a very clear ordering of individual rules. For example, you can't @import one stylesheet halfway through another one, because all the rules in one need to be before or after all the rules in. This would create half of a style rule having lower precedence than another rule, and half of it having higher precedence.

    It also would create another situation where the result with preprocessors (which must always turn nested rules into sibling rules) would be different from the result with the new syntax.

    An intentionally trivial example, to be sure that the two selectors have equal specificity:

    body { 
      color: indigo;
      * & { 
        color: cyan;
        background-color: red; 
      }
      background-color: blue;  
    }

    In SCSS, the nested rule compiles to come after the outer rule, and the page is cyan text on red. In Tab's proposal it would be cyan text on blue.

Points 1 and 3 of that list can probably be discussed as proper issues as soon as [css-nesting] is converted to a proper draft spec. Point 2 is more of a head's-up for anyone getting excited about Sass nesting coming to CSS.

@tabatkins
Copy link
Member

we would need to decide whether a, b { & c {prop:val}} expands as a c, b c {prop: val} or as :matches(a,b) c {prop: val}

The draft currently specifies it as the latter, and I find it very unlikely that we'd change off from that. Changing would require either actually expanding under the hood (with the attendant multiplicative blowup), or implementing the careful actually-matched-path logic that we explicitly rejected forcing implementors to use for :matches().

It's worth calling out that Tab's proposed & is less powerful than the SCSS &.

Agreed, I can add a section to the intro about this.

Omitting the & for parent-child relationships.

Intentional, as I don't want to privilege the descendant combinator, and I personally think it's less clear what's going on.

Extending a single selector token, for example to create BEM-style modified classes

Yeah, very intentionally not allowed. It causes parsing issues, for one (you can't arbitrarily split up an ident and be guaranteed that both halves are still idents), and it's grammatically ambiguous with tagname selectors.

[Relative ordering of declarations and nested rules in a single style rule] looks like something that could be an implementation issue and/or a source of authoring issues:

Yeah, I think I need to change that to sort the declarations to the front. Otherwise I have to reflect the relative ordering of declarations and rules in the OM, which'll be nasty and not compatible with my current plans of just adding a .childRules property to CSSStyleRule.

@chriscoyier
Copy link

it is a feature that will get misused for sure.

<div class="polka-dots fontLarge blue new-blue border--radius___L">
  <p style="font-family: "Comic Sans MS;">What.</p>
</div>

(Literally any feature of any language can be mis-used, right?)

@battaglr
Copy link

battaglr commented Jul 5, 2018

@chriscoyier,

Literally any feature of any language can be mis-used, right?

You're totally right, and I agree. 😀👍

What I think is important about the "potential disadvantages" that some pointed out it's that maybe we could use them to improve (if it's possible) this feature to discourage them —not sure how that could be possible.

@tobireif
Copy link

tobireif commented Jul 5, 2018

Perhaps allow only one level of nesting? Probably too draconian ...

@LeaVerou
Copy link
Member

LeaVerou commented Jul 6, 2018

@isellsoap A lot of the "misuse" of existing nesting is based on the fact that it's compiled down to non-nested CSS. These issues go away if nesting is supported natively and never has to be flattened.
Also, I'm not a huge fan of the type of argumentation that is basically "listen to me, I have experience and I'm telling you, this is a bad thing". Appeal to authority is not how we work. You have to list specific issues. If @battaglr did that for you, then what does your comment add that a 👍on his comment wouldn’t?

@isellsoap
Copy link

isellsoap commented Jul 6, 2018

@LeaVerou

A lot of the "misuse" of existing nesting is based on the fact that it's compiled down to non-nested CSS. These issues go away if nesting is supported natively and never has to be flattened.

But the specificity of nested selectors, in the end, is the same, isn’t it?

So

.a {
  & .b {}
}

is the same as writing

.a .b {}

At least I hope I understood native CSS nesting correctly here. For me this means that the nesting obfuscates the specificity by a lot. With compiled and flattened CSS selectors (if we were to use Sass nesting), at least in the end I can look at what the browser actually has to deal with. It’s more explicit that way. I’m not sure if I can get across what I actually mean. 🤔

Appeal to authority is not how we work.

I know and I certainly didn’t intend to generate that impression with my comment.

@battaglr
Copy link

battaglr commented Jul 6, 2018

@tobireif,

Perhaps allow only one level of nesting? Probably too draconian ...

Yeap, my only idea was to limitate the level of nesting... but doesn't make sense to add a feature with arbitrary limitations like that. Linters will cover that, as they are doing today.


Despite my initial rejection to the idea of adding native support for nesting, I realize that the issues I mention in previous comments would be a problem if (1) you agree that "flat" specificity is a good thing and (2) you work in long-lived and or large codebases where many people with different levels of experience add code; in short-lived —or those that don't require much change— or small codebases I don't thing that nesting would be an issue —at least that's my experience.

@jonathantneal
Copy link
Contributor Author

Thanks for fulfilling this request! I will be closing this issue.

Here is a PR to add this spec to the repository: #2878.

For those interested, here are new issues capturing further discussion of css nesting:

@Nodws
Copy link

Nodws commented Jul 9, 2018

That's cool and all but we want a parent selector.
.child < div { }

@tomhodgins
Copy link

That's cool and all but we want a parent selector.

This might be off-topic for this issue about selector nesting.

Could your desired selector .child < div be expressed as div:has(.child) according to how :has() is being specced? If what you want it isn't yet covered by what :has() is specced to do, it would probably be better to open a new issue to discuss this than to comment in this closed issue :)

@tobireif
Copy link

tobireif commented Jul 9, 2018

That's cool and all but we want a parent selector.

You could file a new ticket at https://github.com/w3c/csswg-drafts/issues/new .

@matthew-dean
Copy link

I worry that the use of & in the proposal is going to lead to a lot of confusion, since it doesn't work like Sass's / Less's &. So half your code may need to be flattened, and half can maybe preserve &. When writing in Sass or Less, how do you target which is which? The preprocessing languages don't lose all usefulness, so both of these ecosystems, if this were adopted, would have to re-invent their entire & syntax / usage if people want to target nested selectors as output. Which is a shame, because that would slow adoption and probably lead more to reject using this feature.

I don't have a better syntax suggestion, but I also don't see this as necessary. But, obviously as a Less contributor, I'm biased.

Most "best-practice" style-writing I've seen suggests not really nesting at all, but to use single class identifiers in a BEM-way, like:

.component {
  &--header { }
  &--body {}
  &--button {
    &:hover {} //etc
  }
}

This keeps things organized and provides single class matching for the browser. I do get why adopting that form (partial class appending) would be rejected by a CSS spec, because CSS is looking to define complete selector matching, but that just points to a preprocessor still being relevant, which points to a potential conflict around & usage and output. I think a different syntax is needed.

@AmeliaBR
Copy link
Contributor

@matthew-dean That's a really good point, but this is a closed issue. Could you file a new issue, starting the subject line with [css-nesting]?

@exdeniz
Copy link

exdeniz commented Jul 18, 2018

Add @media to draft. Like this

.foo {
  color: red;
  @media (min-width: 20rem) {
    color: blue;
    @media (max-width: 30rem) {
      color: green;
    }
  }
}

@Garbee
Copy link

Garbee commented Jul 18, 2018

@exdeniz The comment that closed this issue has @rule support listed as one of the issues to be addressed already. So they have been aware of this desire and it will be looked into with specifying and implementing this behavior.

@sheerun
Copy link

sheerun commented Jan 6, 2020

Why is it still a draft and not a recommendation? It's not enabled by default in preprocessors because of it. Many devs use other syntaxes (less, scss) exclusively for the ability to nest style rules. This is a very important issue.

@brenfwd
Copy link

brenfwd commented Sep 2, 2020

Why is it still a draft and not a recommendation? It's not enabled by default in preprocessors because of it. Many devs use other syntaxes (less, scss) exclusively for the ability to nest style rules. This is a very important issue.

+1 on this. This feature would be extremely useful and allow me to get away from using LESS/SCSS which causes significant overhead in my development process.

@Buslowicz
Copy link

Any ideas on the estimates on nesting being a recommendation?

@LeaVerou
Copy link
Member

LeaVerou commented May 6, 2021

Any ideas on the estimates on nesting being a recommendation?

Easy there. Let's get a First Public Working Draft (FPWD) first, then iterate via multiple WDs, then write tests and go to Candidate Recommendation (CR), then Proposed Recommendation (PR), then Recommendation. It's a multi-year process.
Thankfully, you don't need to wait for that for browsers to implement, which I think might be what you're really looking forward to 😄

@Buslowicz
Copy link

Well, this topic is 2 years old, the entire concept idea is even older. I am aware it's not a simple "build and release to all the major vendors" job, but am wondering if it's actually progressing, or is stalled due to anything? Is there a roadmap or something showing progress on this specific spec?
The actual browser support is a different thing, the other problem is that FF and Safari will probably stay away from implementing that early stage of a spec, and if they do, they might do stuff differently across years before final spec is formed.

@cekkr
Copy link

cekkr commented Apr 12, 2022

Couldn't be more in favor of this. Every developer uses css nesting and has forever through sass/less/stylus/postcss/etc, and it seems like the spec is in a solid place. Not having to pre-compile nesting anymore would be fantastic.

Anything new on the western front?
https://www.w3.org/TR/css-nesting-1/

I think that the general basis should be

.main{
  .one{
    ...
  }

  .two{
    ...
  }
}

as

.main .one{
  ...
}
etc...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
css-nesting-1 Current Work
Projects
None yet
Development

No branches or pull requests