103 points · by feross · 3y ago · 159 comments
Also: it would allow things like ".a { &.b { x: y; } }" (which would be equivalent to ".a.b { x: y; }") to be clearly differentiated from ".a { & .b { x: y; } }" (which would be equivalent to ".a .b { x: y; }"). Just ".a { .b { x: y; } }" looks ambiguous between the two, since it doesn't "look like" a descendant selector.
For production code, I'd use it 100% of the time. For just quickly reorganizing some syntax around and copy/pasting things, I appreciate the shorthand version. I wouldn't use it in a codepen in most situations.
For a more technical justification: with optional &, priority is given (by brevity) to the descendant combinator, but what of other combinators? Do they require & or not? It could reasonably go either way. I haven’t read recent proposals, but am very familiar with CSS grammar, and I’m genuinely unsure.
parent {
/* This might or might not work. */
> child {
…
}
}
parent {
& > child {
…
}
}"be conservative in what you do, be liberal in what you accept from others" applies?
So e.g.
.someClass {
:is(a) > & {
font-weight: 700;
}
}
instead of the more intuitive (but impossible) .someClass {
a > & {
font-weight: 700;
}
}If CSS can’t match or improve on the obvious syntax used by sass then they should not implement it.
All of these options are confusing. Nesting is not a requirement for CSS. Just let it go and if you want nesting use sass.
Not a requirement because it’s not in the spec or because developers don’t need it? If the former, the proposal is to make it a requirement. After CSS grid, CSS nesting is probably the most requested feature of CSS for as long as I can remember for web devs. I only use sass these days for nesting and it would be nice if I didn’t need that extra dependency.
Same. I'm using plain CSS on my current project while using the test implementation of option 3, using PostCSS plugins.
BTW, there is a spec [1].
I agree CSS has come a long way. Nested CSS is the one thing I'm waiting for before I completely abandon preprocessors.
Think about the amount of characters wasted on having to write a whole separate rule to add a hover effect or something similar. Sure, better practices could usually make this unnecessary, but there's definitely valid situations for it. If you add up all the extra kb across millions of sites, and all the extra savings minifiers would be able to achieve with this syntax, I'd bet it starts to add up at a certain point
I was sad to see it left out of 2022-interop, but it's definitely the biggest feature I'm waiting for
My understanding is the features for Interop were chosen because there wasn't good interoperability between browsers for them.
With CSS Nesting, once the spec (and the syntax) is finalized, it's going to work the same in all browser engines; hopefully it'll go smoothly and we won't need CSS Nesting be part of Interop 2023.
So... 20 bytes or so? A whopping 20 megabytes per a million websites.
Seems like a very, very, very small optimization.
I decided to not use Sass on my latest project; feels like CSS is at the point where I didn't need it any more. CSS has come a long way.
And this is the problem. For so long there was a technical limitation because parsing complexity, then there suddenly wasn’t a limitation anymore and the existing syntax wasn’t good enough anymore so we’re shooting the moon.
I agree, all of the options are confusing. The only seemingly viable option is close to Sass, but it should just be strict and stop introducing more ambiguity to the grammar which is already absurdly complex.
This is beyond comprehensible. I guess I can never let go of preprocessors.
I wish browser vendors could work around this limitation and stick to Sass syntax. IMHO all of those options seems strange and make it difficult to read.
FWIW, it is not a limitation, it's a conscious choice. If you want to accept arbitrary selectors in option 3, you'll need unlimited lookahead, which limits the types of parser algorithms you can use, which means that _all CSS_ (not just CSS using nesting, every single web page out there) will be slower to parse, which means the web will become ever so slightly slower. And you cannot ever go back after making that choice. Is it really worth it for the few unusual cases that require workarounds, in an already not-super-common feature?
(Disclaimer: I wrote Chromium's CSS nesting support. It currently implements option 3.)
h1:has(+ p) { something: anything; } h1 { something: nothing; }
everything: has(+ p) { something: anything; }; h1 { something: nothing; }
Syntactically speaking these two lines are equivalent except for a single semicolon; the differing first token doesn't change anything about that. And you can absolutely add a custom element that looks like a property name to blur a line further. So in order to see if the first block is a rule or a property, you absolutely have to read up to the first `;`, excluding nested braces and alikes.That said, the main problem is that the property syntax is overly forgiving, not that the nested rule syntax is problematic. Something akin to JS `use strict` should be able to restrict the property syntax enough to allow the nested rule syntax without unlimited lookahead.
Also, looking at your second line: I would say the second part (starting at the semicolon before the h1), is invalidated by the semicolon. No need to lookahead or read up to the semicolon. The first part would always be evaluated first, up to the closing curly bracket. The second part would fail at the first character. I'm looking at this on a phone so maybe I've misread?
Edit: I should add, I'm not disagreeing with your point (I don't think!), just emphasising it
These options are bad, and CSS does not need this.
1. You don't have to use it if it doesn't seem useful to you.
2. Many developers (me included) use Sass and other preprocessors so they can use nesting; it's probably the single most popular feature of Sass.
3. CSS doesn't need nesting but a lot of developers want it, as it improves the developer experience for writing complex selectors.
The line in the sand here is good.
It would be my choice of all 3, if SCSS-style nesting is not possible.
That is my biggest take away from this whole thing. The SASS/LESS syntax is so much easier to read to me.
a:hover {
color: hotpink;
:is(aside) & {
color: red;
}
}
Here, you can't just use `aside &` as this starts with a letter and will confuse the parser. Hence, wrapping with `:is()` is requires.This is probably something I can unlearn but until then it is very jarring to see & everywhere.
Option 1: @nest. Requires either starting a nested selector with &, or prefixing it with @nest if the & should not be at the start.
Option 2: @nest restricted. Always requires starting with @nest.
Option 3: Additional brackets to group nested selectors.
The "option 3" mentioned in this article matches none of those. It's like option 3 without the defining characteristic of the brackets, or option 1 without the required nesting indicator (but now with the restriction that the selector needs to start with a symbol).
None of these options are particularly great. The new "option 3" looks cleanest, but the symbol requirement is going to trip people up.
Isn't this what Sass does? Option 3 seems to me to be exactly Sass nesting except the "&" is required in more places than it is in Sass. I personally love the "&" and already write my Sass that way anytime I nest
I don’t have much of substance to say about option 4 other than that it just feels… gross. I’m sorry, but those butterfly brackets are really extra.
Circling back, I think my preference for option 5 is that I personally moved away from nesting with preprocessors after watching too many developers create specificity bombs in their CSS from selectors nested 4 or 5 layers deep. I think it makes sense for this syntax to have a clear, distinct weight to it. CSS should be meant to be read just like all other code.
Finally, and I won’t spend too much time on this because I’m not trying to be a detractor, I’m not sure this is really high up on my wishlist anymore. Component-based design has changed a lot about the way I write CSS. I’ve found that I write a lot fewer highly-specific selectors these days, and I never have to bother with heavy id/class syntax conventions like BEM anymore for things to be easy to understand either. Those two things alone were big, dangerous motivators for me to use or encounter nesting. Anyway, I voted for option 5.
No. 3 is the knee jerk, in the heat of the moment response; but no. 5 makes the most sense long term.
That being said, I wish I could better articulate my opposition to No. 4. I think it’s because it immediately strikes me as a typo, like if someone was editing some CSS, deleted a selector and then forgot to write a new one back in before committing their work. Others seem to suggest that formatting addresses this, but I’m uncomfortable with that because it’s very subjective.
I feel the same way about python. To me, indentations and spaces are much more for human legibility than the parser's. Something in my brain says that symbols like curly/square braces designate code blocks much more succinctly than white spaces.
However, for someone that started in a language that used white spaces vs symbols, I get how they would feel the opposite.
Having to go back and modify the existing non-nested lines when you just want to add a nested declaration seems like a large source of "oh damn it" errors and twiddling when you are progressively building/testing styling. The same with wanting to keep default and pseudo-class attributes close to each other for human convenience.
In my experience, when I’ve committed this sin or watched others do so, it’s often because some styles that have already been written need to be updated. Writing CSS is really easy. Nesting makes it even easier. The thing I and I think most people struggle with is organizing it. I think nested styles encourage people to go out in search of a defined scope to ammend moreso than it does to encourage them to write a new one (or selector). It’s easy to see a class you’d need, skip a couple levels down the tree and then get excited when you add just that one element or class you think you need and style accordingly… Only to find out later that you created a difficult to debug style bug that pervades the whole site. My hope is that it would encourage people to think twice before going beyond that second or third level and maybe encourage them to create a new style block instead. I’m also not terribly concerned length or effort these days because of tab completion.
I find 5 to be the most consistent and 3 to be mostly cleaner because of what becomes optional.
I started liking option 4 when I started thinking of `} {` as a special "nested stuff here" sequence instead of a set of scope delimiters. True, it would be better if they had used basically any other sequence of bytes for that, but it still bothers me less then that goofy `:is()` requirement.
html {
}{
& body {
width: 100%;
}
}
You have a clear distinction between the "standar" rules for the current object and then a different set of rules for nested ones. While reading css, on the other options you can mix both styles which (specially with the optional & ) can become easy to misunderstand.I find all the examples harder to read and understand than combining classes/elements.
There's a strong argument to be made that nesting is the standard way to write CSS these days (at least among the demographic that responded).
That's probably why you shouldn't do that... ;-)
Come back, DSSSL, all is forgiven.
It's very explicit whereas sass is implicit and harder to understand at a glance when nesting happens, especially when you throw in an & and have styles above and below the nested parts.
Perhaps the two committees should learn a bit from each other.
parent {
...parent rules...
} @nest {
...nested rules...
}
by analogy with `try { ... } catch { ... }` syntax. Looks a lot better than the line noise `} {` thing.An improved option 3 would be to unconditionally require the &.
Another alternative would be to stick with Sass syntax but require nested selectors to use :where:
parent {
...parent rules...
:where(child:pseudo) {
...nested rules...
}
}
and maybe allow :nest(...) as an alias of :where(...), except disallow it at the top level. parent {
...parent rules...
:nest(child:pseudo) {
...nested rules...
}
}
Or play a similar weird trick to the original option 3 and only require :where(...)/:nest(...) for selectors that begin with a letter. But that starts to look a lot like option 3. Especially if you always require &, because then & can be used to disambiguate the child:pseudo parsing problem.I'm not familiar with the past discussion of any of this, though.
1. That's not one of the options.
2. Apple shipped the parent selector [1] in March and Google shipped it in August.
.card {
border: 1px solid;
&:first-child {
border-top: none;
}
background: blue;
&:hover {
background: red;
color: yellowgreen;
}
display: flex;
// etc.
}I may be in a minority, but I think that what-you-write-is-what-your-browser-parses should be ditched as a norm. There should simply be an efficient (binary) format that is treated as an irrelevant implementation detail.
What is even the problem? People use preprocessors, poly-fills, hot-reloading, etc anyway. It isn't 1990s.
All of this tooling is used because of missing CSS features for the most part.
The web browser's ethos is to be a viewing and authoring environment; from Netscape Navigator on, browsers have enabled its users to write HTML and later, CSS.
For that to continue, browsers we can't have web authoring that's dependent on preprocessors, etc.
Another way to think about it: in an alternate universe where CSS had all of its current features like custom properties (a.k.a. CSS variables), nesting and most of the other modern features, there would be no Sass because we wouldn't have needed it.
In our current reality, CSS is maturing to the point where the work-arounds we implemented aren't going to needed for much longer. We can do that without breaking how the web has always worked.
Because of the universality of the web, anyone from a kid in a developing country with a netbook and a text editor to teams at Fortune 500 companies need to be able to author CSS.
It's a non-starter to require all kinds of tooling—preprocessors, compilers, task runners, packagers, etc. to create web content. You can use these tools if it makes sense for a particular situation but it should always be optional.
BTW, browsers already use Just In Time compilers [1] to render CSS as efficiently as possible; all of the tooling you mentioned is mostly to reduce the size of CSS payloads over a network. Regardless if you minify CSS or not, its rendering speed isn't going to change.
With these tools, there's no compiling happening anyway, just transforming one text format (Sass) to another text format CSS. It's not like WebAssembly where code is compiled into a byte-code format that runs in a virtual machine.
[1]: https://webkit.org/blog/3271/webkit-css-selector-jit-compile...
Nesting promotes bad CSS which exacerbates the problems people encounter elsewhere in CSS (like excessive specificity).
Nesting discourages paying attention to the global scope of the language and we already have many solutions to that problem for those of us who like to pretend the global scope isn't there.
Nesting grossly accentuates up front write-time benefits, whilst degrading the later read-time experience, actually making long term support harder.
I know this is why we have shadow dom, but in practice I feel like the shadow dom has caused more problems than it solved.
Now we have a bunch of ::part things being added to make up for the problems, but it's still very difficult to work with.
I'd love to have the ability to put a <style scoped> tag inside a div and have it's rules only apply to the contents of that div, optionally overriding parent styles.
I don't know about the challenges implementing that in the engines, but it seems like it would be straightforward since the functionality already exists, style tags are valid markup almost everywhere in the dom, they're just parsed out and combined. For this you'd just have to track the parent element and bind to it like an ID selector.
This would make web component authoring more pleasant.
Edit: it looks like the functionality I'm asking for has already been considered, partially implemented, and is now deprecated, sadly.
I found this [1] which basically has everything I want, but apparently it's been deprecated, which makes me sad.
Searching, I found [2], is that what you're referring to? It looks like it'll do what I'm after, if a bit less gracefully. Exciting though!
Quite a few comments here aren't happy with any of them.
Like this, but for CSS: https://github.com/wnameless/json-flattener
Sharp observers will notice that flattened declarations look like path expressions.
While CSS selectors are nice, path expressions enable concise drill down to precise modifications (overrides).
For future, every programming language should have intrinsic path expressions. Basically a useful, usable, legible version of LINQ.
--
PS- I really don't get the '&' ampersand. It's like a reference?
"foo.bar { ... }" is sugar for the expanded "foo { bar { ... }}". Makes sense. (No ampersand required.)
But "foo { bar & { ... }}" being the same as "bar foo { ... }" breaks my brain. What's the use case for reversing the parent-child relationship, contrary to the lexical order?
Update: Oh. It's a SASS thing. Meh.
It's like that exercise middle school teachers sometimes do. They had out a worksheet where the directions tells the students to put their pencil down and do nothing. The rest of the worksheet is a series of questions or whatever.
80% of the students don't read the directions and start filling out the worksheet while the 20% who did read them are just sitting there.
That's what the feedback to an official CSS Working Group question has been like so far—people responding without having read the article; otherwise, they would know that…
1. Because of the way browsers work, the Sass syntax isn't an option—full stop.
The person who implemented Chromium's nesting support explains in the thread [1] why Sass's syntax is not an option. IMHO trying to revive a discussion about wanting the Sass syntax at this point is unproductive to say the least.
I've been using Sass and Stylus pretty much exclusively for a bunch of years—I get it. But that ship has sailed a long time ago, so let's not spend a lot of time on something that's not going to happen.
2. Perhaps before you respond, you should get up to speed on the issues at hand? There are links in the article you may want to read before you respond.
3. Here's what's arguably the most important thing to consider:
Which is best for the future of CSS? When people write CSS thirty years from
now — long after today’s habits and expectations are completely forgotten,
when future generations have never heard of Sass — which option will make writing
this language easy and elegant?
This requires thinking beyond your personal preferences or what you and your team have been doing for the past 10 years. It's about what's best the future of CSS for the long term.We weren't writing Sass 20 years ago (Sass made its appearance in 2006) and we won't be writing Sass 20 years from now [2].
If you think about it, nesting is one of the top reasons why devs use Sass today; once CSS nesting is enabled in all three browser engines, a lot of devs won't feel the need to keep using Sass for every project.
I know there are other features and workflows that Sass/Less/Stylus enable but as far as authoring stylesheets goes, nesting is huge.
This isn't like the old days when it took years before you could use new CSS in production—Chrome already has an implementation (I've used it) and once there's agreement on the syntax, I can't see why Apple, Google and Mozilla wouldn't be able to ship it Q1 2023.
So think about what's best for CSS and the web based on where things are headed—this isn't about you. Okay, it's not entirely about you and your team; but it's mostly about us— current and future web developers.
We're going to need to live with this choice for many years to come.
Let's not screw this up.
[1]: https://news.ycombinator.com/item?id=34007053
[2]: To be pedantic for a second (this is Hacker News after all ;-)), yes, someone will have to work on some legacy codebase 20 years from now that has thousands of lines of Sass… I get that. But we're getting close to a point in time where the vast majority of new web projects will not need to use Sass.
My opinion is: provide a slow parser for my kilobytes of “style.kbcss” and do whatever you want with minified bootstrap megabytes and such. If you don’t feel like counting this opinion, fine. Build pipelines or makefile-likes or just a caching middleware is not a deal big enough to make drama out of it.
I see why you may find uninformed opinions irritating, but the only constructive thing here is to make your comment softer and put it into the header of that site. People may not visit links, may not understand what/why or may (surprise) not care about implications. If you care to make a poll that excludes some opinions in advance, prepare the auditory correctly.
If it’s not gonna be similar to any existing implementation for doing css then don’t bother doing it.
The last thing we need is a shit version of nesting. The syntax we have now is good, it’s what we know, it works. There’s no need for stupid filler syntax to work around scenarios. I.e prefixing with @nest.
Respectfully, we already have @supports, @keyframe, @font-face and several others. Is it really that big a deal?
<link rel="stylesheet" type="text/sass" href="style.css">
And certainly it breaks compatibility with older browsers which won't know what to do with it.It says: "If they see a sequence like element:pseudo, they’ll parse the entire style rule as if it were a property: value declaration.", but why can't the parser be modified to work like Sass parser?
Maybe it's obvious for someone who has deep parser knowledge, but for someone who only has a superficial knowledge, this is not clear. If Sass can transform .sass into .css, what's stopping Chrome from embedding the full sass software and preprocessing all css files with it, *if really wanted too*? While not ideal for obvious reasons, what I mean is: it seems to definitely be possible to do. Does this all just boil down to "we don't want to have the work of rewritting the CSS parser"?
An example that I think it's easy to understand: suppose you are reading a csv string of numbers that can be in base 10 or base 2.
Option a is something like "32, 101b, 101" (aka binary numbers have a "b" suffix, decimal numbers don't)
Option b is the same but the "b" is a prefix "32, b101, 101"
Now think that you can only "see" one character at a time, so you see "3", then "2", then "," and so on. Which of the two options is more efficient to parse?
The answer is option b. With option a you could read a sequence of millions of 1/0 digits but you don't know if it's binary or decimal until you read the final "b" or a "," (or end of file) so you can't do anything but remember all the digits until the end, when you can finally do something with the number. With option b you know in advance if it's going to be decimal or integer (whether you receive a "b" or directly a digit) so you can do all the optimizations right away before even start reading the number!
It's not a matter of whether it can be done or not (of course it can) but the complexity and slowness it can become.
I'm tired but here goes…
Parsing the proposed syntax isn't the real problem; it's parsing plus executing the selectors. Long story short: CSS is programming language that uses a JIT compiler to render CSS.
Sass doesn't run anything; it just transforms one text format into another text format; it's the browser runs the CSS.
Compared to what's required for CSS to run inside of a browser, interface with HTML, JavaScript and SVG (for starters), the Sass parser is trivial in comparison.
> Does this all just boil down to "we don't want to have the work of rewritting the CSS parser"?
Seriously, that's a non-starter for a code base the size and complexity of a browser engine. Not to mention it could mean throwing away years of work on these browser engines.
It's way too late for that… Chrome already has option 3 implemented; to rewrite something would delay this by… a few months? Maybe a year?
Think about it: should Apple, Google, Mozilla, Microsoft, Igalia rewrite code that's already running successfully for billions of users to accommodate whiney developers, many of whom are going to keep using Sass anyway, no matter what they do?
I doubt any of us, if we were leading these teams, would think rewriting major portions of the browser engines makes any kind of sense at this point.
Browsers handle CSS in a way that invalid CSS is ignored. This way, when you add new syntax to CSS, older parsers will ignore just the parts it doesn’t understand, and most (or all of the developer is careful) of the page will will be styled correctly
So in short, browsers have to make invalid CSS work too
There’s no point in supporting nesting if the solution is worse than the options we have right now.
The vast majority of people would rather stick with preprocessors than deal with shit syntax.
If they implement a shitty syntax because of browser limitations they don’t want to fix. People will just use pre processors.
So it’s not about reading or not reading the article. It’s the fact that the options are shit and unless they do syntax similar to what we do now they should abandon trying to support nesting.
.foo { & .bar { color: blue; } }
will have the same precedence rules as
.foo .bar { color: blue; }
in which case it is probably best to avoid the usage in most cases.
Given CSS variables, container queries and various other developments nesting seems like a bad way to organize your CSS.
on edit: to clarify my experience with sass is that people nest overly much, creating very complicated precedence situation that then later they can't figure out why their bar class is blue.
.foo
{ color: red
;}{ .bar
{ color: blue
;} p
{ color: yellow
;}
}
If you make punctuation dimmer in your editor, it becomes a nicely aligned structure, also a toplevel ;} denotes a beginning of a nesting block, it’s like “hey look here as well ;}” and searchable with /^;}{.We don't want that.
For example, CSS Custom Properties (CSS variables) are far more powerful than Sass variables. Plus you'd have two different implementations for how variables work—CSS variables work with the cascade but Sass variables don't. You can't have two fundamentally different methods for variables. That's a non-starter.
Pretty much all of the good stuff from preprocessors is going to be implemented in CSS (including conditional statements) relatively soon; we're just not there yet. But CSS Nesting is an important first step.
Statistically, we do. Sass won the precprocessor wars and nearly every developer prefer SCSS variables over the var(--oh-god) that is CSS syntax.
> For example, CSS Custom Properties (CSS variables) are far more powerful than Sass variables.
Vague. How are they more powerful? Does that offset their downside?
> Pretty much all of the good stuff from preprocessors is going to be implemented in CSS (including conditional statements) relatively soon
It's been a decade plus and we still don't have mixins.
This isn't about which preprocessor is the most popular; it's about the syntax that's going to be used for CSS that we're going to have to live with for a long time.
Look, best practices come and go. Table-based layouts, 960 grid [4], Dreamweaver, special hacks for IE6—we don't do those things any more. With all of the enhancements that have already been added to CSS (CSS Grid, Flexbox, Container Queries, :has() parent selector) and the ones coming—CSS nesting, style queries, conditional, new/better color spaces—using Sass will seem as old-school as including jQuery in every project in a few years.
To quote Denzel Washington's character in the movie Training Day: "We don't roll that way any more." [5]
If you want to go on using Sass, then nothing changes for you; you can even use custom properties in your Sass files. It's not an all or nothing situation.
> How are they more powerful? Does that offset their downside?
Seriously?
There's no functional downside compared to the alternative. The syntax isn't bad once you understand what's going on, but that's subjective anyway. Even if you don't love the syntax, the functionality they enable for developers more than makes up for that.
Sass variables are just static placeholders for values; they're just a step above doing a search and replace in an editor. Very handy when Sass was developed 16 years ago, but very limiting today.
The real question can the dynamic web experiences people come to expect be done only using Sass variables? Are taking full advantage of everything the web platform has to offer by only using Sass variables? The answer is no in both cases.
- they're not part of the DOM and they can't be accessed via JavaScript
- they can't be changed at runtime, such as responding to media queries or other state changes
- can't be used for passing values to and from web components
There are dozens of articles about why custom properties are superior to preprocessor variables:
[1]: https://css-tricks.com/difference-between-types-of-css-varia...
[2]: "Practical Use Cases For CSS Variables"—https://ishadeed.com/article/practical-css-variables/
[3]: "DRY Switching with CSS Variables: The Difference of One Declaration"—https://www.codeinwp.com/blog/css-variables/
[4]: https://960.gs
[5]: https://movie-sounds.org/ghetto-movie-sound-clips/quotes-wit...
> So, a lengthy discussion began about what to do instead. Earlier this summer, the CSSWG debated between Option 1, Option 2 and Option 3. Of those, Option 3 won. Since then, two more options have been proposed, Option 4 and Option 5. If you remember various details discussed across 53+ issues, put all of those older ideas aside. At this point, we are only debating between Option 3, 4 and 5, as described in this article through the set of examples below.