12 ms·
Help choose the syntax for CSS Nesting
- photoGrant 4y agoEmbedded braces, no question!
- martin_a 4y agoDo we really need this? I find all the examples harder to read and understand than combining classes/elements.
- spoils19 4y agoNesting is a solution in search of a problem. Combining classes has worked fantastically for me over the last 15 years.
- gedy 4y agoI don't mind it myself, but a large chunk of devs really don't get it, and they do better with nesting
- culi 4y agothat's great, but sometimes when I start vanilla side projects I like to take a CSS Zen Garden approach to things. That's harder to do the more tightly you couple your HTML and your CSS
- martin_a 4y ago> That's harder to do the more tightly you couple your HTML and your CSS That's probably why you shouldn't do that... ;-)
- adamwathan 4y agoThe stylesheets for CSS Zen Garden examples are more tightly coupled to the HTML than any other CSS I've ever seen in my life. They literally have no use against any other block of HTML than that one page.
- culi 4y agohmmmm. u right Well still I shouldn't have to decorate my html for css to something I feel is pretty reasonable to expect it to support
- jjcm 4y agoFor me it's the opposite. I find the nesting far easier to parse, especially when deeply nested. One thing to consider is what the average dev uses - looking at the 2021 state of css ( https://2021.stateofcss.com/en-US/technologies/pre-post-processors https://2021.stateofcss.com/en-US/technologies/pre-post-proc... ), SASS was used by 90% of responders, and of those 84% of them were satisfied with it. 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).
- butz 4y agoWasn't this already asked by Chrome developers? Or each browser is implementing nesting in their own way?
- FinnLeSueur 4y agoIf you open the article you will find this as the 4th paragraph: > 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.
- slinger 4y ago> Everyone wishes CSS nesting could use the same kind of simple syntax that Sass does. That’s impossible, however, because of the way browser parsing engines work. 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.
- Sesse__ 4y ago> I wish browser vendors could work around this limitation and stick to Sass syntax. 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.)
- somishere 4y agoPossibly a stupid question. But is there a reason you couldn't include 2 engines? And require e.g. a doctype assertion?
- Klonoar 4y agoBecause it's the same result as if you just included the slower one, since there's mindshare for the SASS variant already - it'll just become defacto standard, and slow down the web. The line in the sand here is good.
- somishere 4y agoI guess the idea would be something along the lines of a 'strict' tag, to identify a shift to modern syntax with stricter rules around parsing, that ensures an infinite lookahead wouldn't be required for e.g. pseudos vs properties. I put together a regex last time this was discussed [1] (which obviously completely alleviates all concerns): https://regex101.com/r/aOc2Pz/1 https://regex101.com/r/aOc2Pz/1 But seriously, syntax evolutions happen. If there's an issue with parsing garbage CSS why not just let that garbage run slowly, and re-optimise for the rest, prioritising for form and function. [1] https://news.ycombinator.com/item?id=32248837 https://news.ycombinator.com/item?id=32248837
- LordDragonfang 4y agoOption 3 seems the most intuitive, but I can see the arguments for 5. It's 4 that I'm having a hard time understanding why anyone would want it that way. It's truly awful. I can't think of literally any other language (style, markup, programming, or otherwise) that does nesting with a second set of adjacent (not nested!) curly braces.
- derkades 4y agoLaTeX maybe? But yes, I agree that it's awful.
- halostatue 4y agoSame. I think that the only thing I don’t like about 3 is the need for `:is(aside)` and the like, and I can see that there might be some performance benefit to `@nest {…}` blocks (5). I think the only thing I don’t like about 5 is the required `& {}` block. I find 5 to be the most consistent and 3 to be mostly cleaner because of what becomes optional.
- ezrast 4y agoI find 5 least consistent because there are now two competing ways to define an unnested block: the normal way, and the `@nest { & { ... } }` way. Why would anyone do the second way, you ask? Because that rule used to have a nested rule, and when it was taken out the programmer was lazy or didn't notice that it was the last nested case. Having to completely reformat the base rule just to add or remove a nested case is a complete deal breaker for me. 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.
- TrianguloY 4y agoI voted for 4. For me it's the best option with }{ on a separate line. 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.
- sublinear 4y agoAll these options are pretty terrible yeah. I'd prefer if there was work done towards selectors for parent items, siblings of parents, and children of parent siblings. Not that the work is mutually exclusive.
- alwillis 4y ago> I'd prefer if there was work done towards selectors for parent items 1. That's not one of the options. 2. Apple shipped the parent selector [1] in March and Google shipped it in August. [1]: https://webkit.org/blog/13096/css-has-pseudo-class https://webkit.org/blog/13096/css-has-pseudo-class
- gorkish 4y agoWe want it to work the way Sass works. FFS make it happen and stop it with all this pedantry.
- spankalee 4y agoDid you read the third paragraph in the article?
- toomanydoubts 4y agoI think the question that's not answered clearly is: why can Sass parse it, but browsers can't? 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"?
- neongreen 4y agoSee the comment at https://news.ycombinator.com/item?id=34006622 https://news.ycombinator.com/item?id=34006622
- TrianguloY 4y agoI may be wrong, but I think it's a matter of complexity and speed. An efficient parser knows exactly what it is reading just by checking the next following word (token) and can act before it even reads the whole thing. Sass uses an "infinite lookahead" algorithm that makes it way slower (maybe doesn't matter for 1 file, it does for hundreds). With sass the parsing is made only when compiling the app, so it can afford the extra processing. On browsers, specially mobile, it can become a problem if you need to do it on all css of all pages. 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.
- nailer 4y agoI want browsers to have first class Sass support. Pave the cowpaths etc.
- alwillis 4y ago> I want browsers to have first class Sass support. 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.
- nailer 4y ago> We don't want that. 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.
- alwillis 4y ago> Statistically, we do. Sass won the precprocessor wars and nearly every developer prefer SCSS variables over the var(--oh-god) that is CSS syntax. 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-variables/ https://css-tricks.com/difference-between-types-of-css-varia... [2]: "Practical Use Cases For CSS Variables"—https://ishadeed.com/article/practical-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/ https://www.codeinwp.com/blog/css-variables/ [4]: https://960.gs https://960.gs [5]: https://movie-sounds.org/ghetto-movie-sound-clips/quotes-with-sound-clips-from-training-day-2001/we-don-t-do-that-no-more-that-day-s-dead-dog-we-don-t-roll-like-that-no-more https://movie-sounds.org/ghetto-movie-sound-clips/quotes-wit...
- swlkr 4y agoI actually like Option 3 the best even more than sass syntax. 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.
- jorams 4y agoI'm a bit confused about the constant mention of option 3 in this article, because it seems to match none of the actual options from the original poll. The original poll offered three options: 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.
- culi 4y ago> Additional brackets to group nested selectors. 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
- deleted 4y ago[deleted]
- deleted 4y ago[deleted]
- joeydi 4y agoI think the reason this debate continues to rage on is that all of the options are worse than what is currently available with pre-processors. 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.
- barnabee 4y agoI try not to use preprocessors or bundlers/build tools for simple stuff so the addition of features like this to the base CSS language is something I look forward to.
- RheingoldRiver 4y agoPreprocessors aren't always available though. For example, I almost never have access to one, developing with MediaWiki (there is an extension that makes it available but most of the wiki farms I've worked for have not had it installed).
- Gigachad 4y agoThat sounds like a media wiki problem. CSS provides all the tools you need to produce the results.
- aliyfarah 4y ago> Nesting is not a requirement for CSS. 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.
- alwillis 4y ago> 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.
- janitor61 4y agoI'd say they should avoid bloating CSS, keep Sass style and just use type='text/sass' or type='text/css-nested' in the style tag, but it seems that attribute is depreciated... why is that?
- dagurp 4y agoHow about a new file extension. .css2 or.xcss or something?
- alwillis 4y agoThe type attribute is not deprecated… but of course, no browser supports anything like <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.
- wruza 4y agoThey don’t know what to do with options 1..5 neither.
- claytongulick 4y agoI like option 3 the best, but what I'd really prefer would be block-scoped css blocks that could optionally be scoped just to children of the parent tag. 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.
- Sesse__ 4y agoHave you looked into @scope?
- claytongulick 4y agoI haven't! 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! [1] https://css-tricks.com/saving-the-day-with-scoped-css/ https://css-tricks.com/saving-the-day-with-scoped-css/ [2] https://drafts.csswg.org/css-cascade-6/#scope-atrule https://drafts.csswg.org/css-cascade-6/#scope-atrule
- Sesse__ 4y agoYes, the latter. At least Chromium-based browsers support it behind a flag (ie., you can't use it on the web yet, but you can experiment with it and file feedback). I don't know if Firefox does, too, but they very well might.
- DitheringIdiot 4y agoWithout a "none of the above" option, it's hard to tell what people really want. Quite a few comments here aren't happy with any of them.
- TrianguloY 4y agoBut option 3 from the previous poll is not the same as option 3 now...I don't understand
- alwillis 4y agoSo far, most of the responses are pretty underwhelming. 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 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.
- TrianguloY 4y agoCould a backwards parser work? With the Sass syntax I think doing the parsing backwards can be made without lookahead. Probably it has other issues though...
- LudwigNagasena 4y ago> Everyone wishes CSS nesting could use the same kind of simple syntax that Sass does. That’s impossible, however, because of the way browser parsing engines work. 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.
- Gigachad 4y ago
- alwillis 4y ago> 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.
- LudwigNagasena 4y agoEverything is still going to be tree-shaken, minified and mangled before being transferred to the client; no matter how much bells and whistles are added to web languages. Why not just make it decoupled and efficient? Compiling code isn't a radical idea.
- alwillis 4y agoAs pointed out in the article, the nesting syntax has to work in every setting that CSS works in today and has always worked in—from a hobbyist working alone on a side project to teams working on huge code bases and everything in between. 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-compiler/ https://webkit.org/blog/3271/webkit-css-selector-jit-compile...
- jasonhansel 4y agoI prefer Option 3, but IMHO the "&" should be required in all cases. Having it present in some places and absent in others makes the resulting code less readable, more ambiguous, and generally harder to understand. I'd rather keep things simple and uniform, even if it costs extra keystrokes. 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.
- jjcm 4y agoI don't think it needs to be required, but I'd 100% include that in any linter or style guide I had for code. 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.
- chrismorgan 4y agoI very strongly agree. Mandatory & makes things much clearer, for a negligible cost. (And really, the curly braces, colon and semicolon are all mandatory (well, except the last semicolon of a ruleset), and alternative syntaxes with less punctuation like Sass’s have failed; the & is frankly more consistent than its absence.) 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 { … } }
- jasonhansel 4y agoThis is another good point, particularly because (IMHO) people tend to overuse the descendant combinator in places where they should really use the child combinator instead.
- 4y ago
- runarberg 4y agoIt feels weird that the CSS WG does a popular vote for a different syntax implementing the same feature, something that an expert opinion should weigh way more then popular demand. But at the same time TC39 picked an archaic version of the pipeline operator (|> https://github.com/tc39/proposal-pipeline-operator https://github.com/tc39/proposal-pipeline-operator) despite a clear demand from the community to pick a functional one. Perhaps the two committees should learn a bit from each other.
- jacobp100 4y agoThe version they’re picking is the fast pipe from OCaml, and the only pipe in ReScript. It works much better for type inference, and avoids the extra allocations the FP pipe usually incurs
- CSSer 4y agoWow. I’m really surprised so many people have voted for option 3 so far. Option 5 feels much more in line with the rest of the other proposals and features in CSS, and option 3 introduces at least one quirk we’ll have to internalize and teach to everyone forever. Those suck. I have to teach those kinds of things to juniors until my throat is sore some days. 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.
- alwillis 4y agoThanks for the thoughtful response. No. 3 is the knee jerk, in the heat of the moment response; but no. 5 makes the most sense long term.
- CSSer 4y agoThe web has given me an amazing career and life (that I feel is still very much only getting started). I’m always happy to contribute when I can. 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.
- 4y ago
- inopinatus 4y agoOne could be forgiven for thinking any committee depraved enough to enumerate the options sequentially as 5, 4, or 3, moreover where option 3 is not even the same as the prior option 3, has implicitly renounced any standing to be offering solutions in re. developer ergonomics. Come back, DSSSL, all is forgiven.
- sfink 4y agoI claim that an improved option 4 would be: 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.
- Tyr42 4y agoGiven the rules at where I work, we aren't allowed to use elements case rules anyways, so Option 3 has no downside for me haha.
- mieko 4y agoIf you're being micromanaged to the point of "allowed" CSS selectors, perhaps you should branch out a bit?
- chadlavi 4y agoThis is a solved problem. Use the SASS syntax. I don't know why it's even a question.
- account-5 4y agoAm I the only one who prefers unnested? It seems to make more sense to me.
- deleted 4y ago[deleted]
- wruza 4y agoI like the idea of using newlines to alleviate some syntactical issues. Here is what I came up with after experimenting with option 4: .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 /^;}{.
- captainmuon 4y agoPersonally, I don't need the ability to place '&' anywhere. Just extending selectors at the end is sufficient. So I would greatly prefer a SASS-like syntax that they excluded.
- bryanrasmussen 4y agowhat will nesting do to the cascade rules - I suppose that .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.
- frosted-flakes 4y agoOne big advantage of option 3 is that it allows for putting properties and nested selectors in any order, rather than segregating them in different groups. This is already possible in Sass and I do it all the time. For example: .card { border: 1px solid; &:first-child { border-top: none; } background: blue; &:hover { background: red; color: yellowgreen; } display: flex; // etc. }
- sheerun 4y agoSo why exactly & would be required before element selectors? Syntax parsing rules can be different for nested blocks. It's not a breaking change.
- deleted 4y ago[deleted]
- padmi 4y agoOf course option 3 but make "&" required. And ":is(aside) &" is ugly, should be just "aside &". Yes, it starts with letter, but it's the only way to be not ugly.
- deleted 4y ago[deleted]
- lukewiwa 4y agoI feel like option 4 is about the only one with somewhat sane indentation. At least in conveys what level the nesting is on for the root nesting element.
- the_other 4y agoControversial opinions follow: 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.
- deleted 4y ago[deleted]
- deleted 4y ago[deleted]
- specialist 4y agoWhichever option the boffins decide, nested and flattened should be isomorphic. And used interchangeably. Like this, but for CSS: https://github.com/wnameless/json-flattener 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.