14 ms·
WebKit Supports Nested CSS
- SamEdosa 4y agoThis is great! The only reason I use SCSS is for the nesting. It should have been implemented 10 years ago, but better late then never.
- dgb23 4y agoIt's great that parts of SCSS are getting superseded by CSS. Nesting is great to avoid selector repetition. Custom properties (CSS variables) and CSS functions give us tools to avoid magic numbers and to encode layout relationships. New sets of selectors and container queries let us decouple and re-use declarations more. CSS Houdini gives us further power in extending CSS functionality. Of course there are things that SCSS provides which are unlikely in the scope of future CSS proposals such as datastructures (maps) and loops to generate classes and mixins. But I can already imagine a world were those aren't necessary anymore for many cases.
- brewdawg 4y ago> SCSS are getting superseded by CSS. Reminds me of how Coffeescript died out because its best ideas got integrated into Javascript. What I want to know is: how the hell did this take so long? Nesting is such an obviously useful feature to have in CSS, and once I'd experienced it in SASS I never wanted to be without it. Why did it take 10+ years for this to be introduced to CSS, especially when other browser-based technologies like JS have evolved enormously in that time?
- patates 4y agoFor another take: I try to write a single module.css file per component in which I do zero nesting, avoiding any preprocessors (other than postcss modules, obviously). Nesting, IMHO, makes CSS a bit easier to write but much harder to read.
- psygn89 4y agoSome of the Less/Sass maintainers are also active parts of the communities that write the specs and I guess when the idea of nesting was fresh to these preprocessors they didn't feel compelled to make it a core part of css with how widely the preprocessors were getting adopted. While I don't doubt our computers 10+ years ago could parse through nested styles it's probably really trivial now and thus being implemented into core. As far as the speed of which things get implemented, I often feel there is a lack of understanding where design and development overlaps. Most devs are just devs in the sense they solve algorithmic/browser rendering problems, and don't really dabble enough with markup/styling languages like HTML and CSS to hit the pain points of using them. And the people that deal with markup/styling do not know the proper channels to rally behind some of the ideas that would make their lives easier. Unfortunately, there are less individuals that are proficient at markup, styling, and programming (not just in the sense of coding in JS/TS, but understanding the internals of the browser and programming for it), and the unicorns that do understand are often snatched up by Google/Microsoft/etc. which often have their own agendas. I feel there's just a lot more niche backdrop knowledge that is required to get the ball rolling. These are just my feelings on this matter, I could be wrong.
- amjnsx 4y agoFor me this is where something like PostCSS shines. You simply write future css and remove the plugin when it’s supported natively. This wins in my opinion because there shouldn’t be any conversion necessary from something like Sass to CSS
- tehbeard 4y agoWhat's the hit/miss rate on that CSS changing syntax? I Vaguely recall something similar happening with decorator syntax/how it worked in JS/typescript. Or do you keep to CSS features that are locked down in terms of spec, just waiting on implementation to roll out?
- amjnsx 4y agoIt’s your call fortunately/unfortunately. The safe option is obviously to install plugins for features that are close to passing as possible, where the api is stable at least - but there are plugins for very early stage proposals too.
- nobleach 4y agoThat decorator syntax thing was a mess. The original syntax seemed like it was far enough along. Many folks adopted it because it seemed like "a sure thing". I ended up pulling it from a project in 2017 because so few of the folks on my team wanted to truly understand what problem those were meant to solve. It was easier to "decorate" in a more manual way (wrapping a function with a function). The way TC39 handles stages now should stop things like that from happening. (You implement a Stage 1 or 2 feature fully knowing it could change)
- tambourine_man 4y agoWebKit is on fire lately, awesome. We only need an autoupdate feature for Safari. Badly. It’s the only not evergreen big browser, to my knowledge.
- chrisweekly 4y ago"CSS Nesting will work just like Sass, but with one new rule: you must make sure the nested selector always starts with a symbol." I think I like it. In general I like the adoption of good features like this. But. It's getting awfully hard to keep track of CSS vs SASS syntax. Starting a greenfield project today I'd leave SASS out of it... but I'm usually working on projects where SASS is already present. Shrug.
- JonathonW 4y agoAt this point, I'm using SASS pretty much exclusively for nesting (and where required to customize other styling systems-- mostly older Bootstrap). Once I can assume CSS nesting is everywhere I need it, I can probably eliminate SASS in most places where I'm using it. (I'd also like more/better color functions out of vanilla CSS. But that's not necessarily a dealbreaker for me in most cases.)
- rockwotj 4y agoI would recommend using PostCSS. It allows you to compile future CSS for browsers today. When you feel comfortable with browser support you can just remove the processing step
- culi 4y ago> Back in December, we wrote an article detailing three different options for CSS Nesting. > Web developers responded to the poll with great clarity. Option 3 won in a landslide. Yup, pretty much. The only thing I really wish won however was making the beginning "&" always required for nesting. Instead you're able to omit it if there's any other symbol. Example from article: main { .bar { ... } #baz { ...} :has(p) { ... } ::backdrop { ... } [lang|="zh"] { ... } \* { ... } + article { ... } > p { ... } ~ main { ... } } The position of requiring & was not represented in the poll but seemed really popular in all the comments and seems like it would only make the parser's job easier (both now and in the future of CSS) Regardless I'm just happy it's finally here! Hard to see the use-cases for sass in 2024 but, like jQuery, it's definitely made its mark on the history of the development of web standards
- rockwotj 4y agoI remember the main argument against this is that you can always enforce this with a linter and either way it's not a slower parser, maybe slightly more complex. Personally I do agree and I like the explicitness of always having the &
- culi 4y agoYeah that's fair and I admit don't actually know anything about the parsing implications. I guess really I'm just looking for an excuse to convince my coworkers to adopt this practice without coming off like I'm bikeshedding haha
- rockwotj 4y agoI think you could argue for the clarity (code is read more than written) and consistency (why do I need this here and not in other places?)
- chrismorgan 4y agoRelevant links on this: https://twitter.com/LeaVerou/status/1580215877705687040 https://twitter.com/LeaVerou/status/1580215877705687040, a poll about this specific matter (with links to other relevant polls which on the surface contradict this one). https://github.com/w3c/csswg-drafts/issues/7834#issuecomment-1302427773 https://github.com/w3c/csswg-drafts/issues/7834#issuecomment..., on this exact matter (chosen as a convenient starting point, after matters were already settled, but the whole issue is about it). By the time this poll was done, they had already decided not to consider mandatory-&, though I don’t really understand why (it’s pretty obvious to me that dividing into 3a and 3b would have been much more interesting than a couple of the other options which were straw men that no one was capable of taking seriously even if they tried). https://github.com/w3c/csswg-drafts/issues/7961 https://github.com/w3c/csswg-drafts/issues/7961, about doing away with & in all cases for descendant selector (… which would be terrible for complexity and worst-case performance, and is only being considered because they already made things inconsistent by making & optional in every other case). (I don’t like where it’s ended up, and consider requiring the & in all cases to be obviously materially superior, for both machine and human handling, and that there’s clear concrete advantage in having the requirement as an actual language rule rather than only a linter-enforced choice. People are far too hung up on exactly Sass syntax.) > it would only make the parser's job easier Mind you, it’s not a big difference; it’s just “if there’s no & in the selector, insert one and a descendant combinator at the start” in some shape, which could be as little as half a dozen lines of code net.
- frosted-flakes 4y agoWill nested CSS support mixing properties and nested rules in any order, or do all the nested rules have to grouped together at the end? Right now, I frequently write SCSS rules like this: .some-class { background: blue; &:hover {background: red} border: 1px solid; &:active {border: 1px dashed} padding: 16px; display: flex; gap: 8px; & > * { color: red; } } And it would be a pity if that wasn't allowed. The reason I ask is because I seem to remember an early proposal not allowing this, but I can't find where I read it.
- mtber 4y agoAs I understand it, you can mix it but the parser will hoist all the immediate some-class styles to the top
- culi 4y agoWhy would it not support it?
- frosted-flakes 4y agoI don't know, that's why I'm asking.
- culi 4y agolol just curious what the thought process is. Sass and postcss support that and every other css flavor with nesting I've used supports it and it seems like it'd be a pretty big deal and something that would be explicitly called out in the article if it didn't support it. So I'm just curious if you've run into an issue with that or if there's some in-the-weeds technical reason why that might not be supported
- frosted-flakes 4y agoMy memory was correct. I found the section in the original proposal[1] that did not allow mixing nested rules and declarations: > When a style rule contains both declarations and nested style rules or nested conditional group rules, the declarations must come first, followed by the nested rules. Declarations occuring[sic] after a nested rule are invalid and ignored. [1] https://www.w3.org/TR/2021/WD-css-nesting-1-20210831/#mixing https://www.w3.org/TR/2021/WD-css-nesting-1-20210831/#mixing Fortunately, this has been changed in the most recent proposal[2]: > When a style rule contains both declarations and nested style rules or nested conditional group rules, all three can be arbitrarily mixed. However, the relative order of declarations vs other rules is not preserved in any way. [2] https://www.w3.org/TR/css-nesting-1/#mixing https://www.w3.org/TR/css-nesting-1/#mixing
- a1371 4y agoAwesome to finally have nesting. The way I see it, this took 10 years longer than it should have. I feel the only big thing missing from the vanilla stack for me right now is a template element that multiple html files can share. Just like how you make a blog header in Jekyll or Hugo and it adds it on all your blog posts get the header. I haven't found an easy way of doing that if I have a bunch of html pages.
- nightpool 4y agowell, the classic solution has always been to use an iframe :p
- a1371 4y agoI don't know if that's actually an ok method or not, but I thought of that and looked around for it with little luck
- alxmng 4y agoThat's what an iframe is? I guess there could be a partial element that works like <partial href="header.html" /> but if it's referencing HTML, what about JavaScript or CSS it includes? That's exactly what iframe handles.
- robgibbons 4y agoWhat you're asking for is called Server-Side Includes, it's been a feature of Apache for ages, but is also supported by Nginx and other servers.
- miragecraft 4y agoWe had it briefly in the form of HTML imports, but the powers that be removed it because it’s not powerful enough for JavaScript/web apps development; totally ignoring the fact that the web isn’t just about apps.
- wnevets 4y agooption 3 really was the best option
- bikeshaving 4y agoIs there a PostCSS or similar plugin which enforces this nesting syntax (& required for element selectors) so we can be ready for when this is widely adopted?
- culi 4y agoPostCSS has supported CSS nesting for many years now. The nesting standard has changed pretty minimally over the years and the PostCSS team has done an excellent job keeping up One of the main reasons I never used CRA for my miniprojects was because the first thing I always wanted to do was set PostCSS up with nested CSS support which was a pain to do in CRA
- frosted-flakes 4y agoWhat do you use now? I'm currently using Create-React-App for one of my projects and some parts of it are really frustrating. For example, you can't create a Web Worker script without ejecting, or using some tool that intercepts and alters the CRA Webpack configuration. Should I just bite the bullet and figure out Webpack (or another bundler) from the basics? I feel like that will be inevitable at some point anyway.
- culi 4y agoTbh nowadays I use every new project as an opportunity to try something new. I'm in between a Fresh project, a Svelte project, a PWABuilder project, and a Qwik project. They all have their use-cases and {dis-}advantages so it's nice to know a lot of different tools for different jobs But I've realized a lot of my projects can actually get by pretty far with just vanilla html/css/js and a good reset.css so I have a template for that that I continuously update and I've actually found that to be the most productive. Though that's likely a function of not having to learn something new unlike all my other projects There's been suggestions on the React repo of dropping the suggestion to use CRA from the docs entirely since it's pretty outdated and not really in keeping with React's current philosophies.
- throwaway284534 4y ago
- bruce511 4y agoThis is an excellent step forward for css, and frankly it's nice to see safari take the lead for a change rather than lag behind. It'll be about a year or so before I'm comfortable using it in production code (assuming it comes to Firefox soon, and presuming it'll get into Edge by default.) But a year goes past quickly these days, and at least the clock has started ticking.
- EMIRELADERO 4y agoI don't know anything about WebKit development processes or community management, so please forgive me if I say something wrong. Isn't it interesting how the engine has been implementing new features and generally running on a lot of steam coincidentally since the EU's Digital Markets Act (which will force other web engines on iOS) went into effect? Or maybe the dev process and community interactions has always been like this, in which case disregard what I just said and feel free to correct me.
- culi 4y agoDidn't it go into effect in September 2022? Safari took a leading role in interop-2022[0] from the very start. So the change in Safari's philosophy stretches back at least to start of 2022, but they've also led the way on adoption of a number of other web standards like the new colorspaces which they've had since 2021 and which Edge and Firefox still don't support (well, FF has a feature flag) [0] https://wpt.fyi/interop-2022 https://wpt.fyi/interop-2022
- pancrufty 4y agoDoesn't sound interesting to me. Safari also implemented a very popular feature first a year ago, long before that act (:has() selector). Even if Safari were to be the best browser ever, I don’t think that would save Apple, so any development effort would be futile (especially compared to lobbying)
- satao 4y agoHistorically the webkit team has pushed the web possibilities a lot. Just take a look at the amount of APIs that you had to add the `webkit` prefix, for example. Not sure if you work with browsers, but constantly you meet something that they implemented first. I honestly think that developers are very wrong when they think that Safari/webkit is slowing the web down. Yes, some things like lack of notifications etc are very annoying, and they could've been implemented. But I still prefer this approach over the Blink one, where they develop half-baked ideas just to track you better.
- doodlesdev 4y ago
- LAC-Tech 4y agoWhenever I see nested CSS, I always think the non-nested version is cleaner. Then again, I'm lucky enough to often work with my own 'hand-crafted', semantic html, and not some div soup generated by a tool.
- culi 4y agoI generally agree and wince at anything deeply nested, but there's no question that the biggest benefit here by far will be pseudoclasses. Especially when you wanna do something to children elements based on a pseudoclass .page form border: 2px solid #223; border-radius: 0.15rem; & button { background-color: red; transition: background-color 0.15s ease; } &:hover button { background-color: blue; } } seems way cleaner, easier to read, and more maintainable than the alternative which I don't even wanna type out
- josephg 4y agoYeah I agree. Most of my CSS files end up feeling like a big, append-only list of selectors for seemingly random stuff. Its so hard to tell if there are selectors in there that are no longer in use. I really like the look of nested selectors for this reason - because I can group my selectors by component.
- supriyo-biswas 4y agoYou could always use tailwind - the problem of CSS classes no longer in use is the exact use case for it.
- transfire 4y agoAm I missing something… isn’t it just a simple substitution? .page form { border: 2px solid #223; border-radius: 0.15rem; } .page form button { background-color: red; transition: background-color 0.15s ease; } .page form:hover button { background-color: blue; }
- 4y ago
- chadlavi 4y agoPut it in my veins!!!! Finally!
- kijin 4y ago:is(article) & That looks hacky at best. The excuse of parsing performance is responsible for so much weird syntax in web standards today. The standards are literally being dragged around by browser vendors' priorities. I wish they would do it the other way around for once: come up with the cleanest, easiest-for-humans syntax as possible, and tell browser vendors to fix their damn engines. Perhaps this will lead to the development of a new CSS engine that's actually optimized for the latest goodies. Instead, for the last decade or so, we've only been getting bits and pieces of half-assed imitations of Sass. Better than nothing, of course, but still seriously lacking.
- culi 4y ago> come up with the cleanest, easiest-for-humans syntax as possible I'm definitely on the opposite end of this argument. I really think browsers should be focusing on efficient and theoretically rock-solid foundations. The fact that web standards are slow to evolve and become adopted is a feature, not a bug. If you visit a create-react-app project from 2 years ago you probably couldn't get it running today. I would like a web where a hand-made site from a decade ago still works The global web standard should be reliable and efficient. Syntactic sugars should be left to the ecosystems and only adopted when they don't confer performance tradeoffs
- spankalee 4y ago> tell browser vendors to fix their damn engines Parsing performance of the type they're talking about is an algorithmic fact, not an implementation problem. Your suggestion is like telling engineers to fix the laws of physics.
- kijin 4y agoThe fact that the article raises the possibility of this limitation being removed in the near future means that it's not a law of physics, only a matter of finding a better algorithm. Even if it were a law of physics, engineers can often circumvent laws of physics using smart caching and other tricks. We've been waiting for this feature for decades already. It would have been better if they'd just invested a couple of more years to come up with a better parsing algorithm before standardizing a halfway implementation.
- nailer 4y agoThis half assed version of nesting is lame, as are all the others. Just give us SCSS its been ten years now, pave the cowpath.
- culi 4y agoWhat's the difference between this and SCSS nesting? It seems pretty full-featured to me. What's missing?
- rezonant 4y agoYeah... the only difference _in terms of nesting_ that I'm aware of is exactly as discussed in the blog post: you must start a nested section with a symbol. Sass itself has a huge amount of features... is the expectation that we should just adopt a Sass implementation into the browser or something?
- frosted-flakes 4y agoThe other difference is that SCSS nesting can also be used for string concatenation, as in BEM classes. Such as: .some-class { color: red; &__child { color: blue; } } Which compiles to .some-class { color: red; } .some-class__child { color: blue; }
- culi 4y agoOh right I kinda hate that and feel like it leads to strangely named classes
- nailer 4y agodialog { background-color: white; color: black; input { width: 200px; } } Doesn't work.
- cphoover 4y agoMaybe I am an outlier... but I really don't like nested style documents like those founds with SASS, LESS, PostCSS. When the number of nested selectors becomes too great it can become very difficult to reason about. I would never use this without some kind of lint rule enforcing a maximum depth of selector nesting. I agree with the other commenters ITT taking the position flat CSS looks cleaner than nested documents.
- rezonant 4y agoThe difficulty you mention is definitely an issue, but the insane repetition required for even a modestly complex piece of UI when using "flat" CSS is worse, in my opinion. I suppose there might even be a slight efficiency gain over the wire once Sass outputs nested CSS by default.
- pier25 4y agoI wrote flat CSS for many years and yeah it's a lot of work but also I find it becomes more difficult to parse visually. Like when writing HTML or regular code, I find indentation helps me parse and navigate the structure very easily. There are cases with complex components where it can become a bit complex, but it's trivial to split the tree in multiple parts to reduce the indentation.
- jakelazaroff 4y agoI agree: even when I use preprocessors, I rarely nest “normal” selectors. The real win is nesting pseudoselectors (:hover, :focus, etc) and media queries.
- JimDabell 4y ago> When the number of nested selectors becomes too great it can become very difficult to reason about. This is a sign you need to decompose whatever design you are working on into smaller components. If you’re trying to write styles for a whole page at once, you’ll see this problem, but if you are working on small components, it’s very rare.
- 4y ago
- infogulch 4y agohttps://caniuse.com/css-nesting https://caniuse.com/css-nesting So it's the latest chrome, Safari technical preview, and edge behind a flag. No disposition from Firefox yet afaict.
- dagurp 4y agoChrome dev. The latest stable version is 110
- jeroenhd 4y agoMozilla has come out on support of the standard but I'm not seeing much on the Bugzilla tracker. May be a while until it's supported, especially since modifications like these also impact functionality like the syntax highlighter and the dev tools.
- c-smile 4y agoNested rules is just a syntax sugar. In Sciter, 10 years ago, I came up with style sets: @set Main { :root { ... } // root element that has this set applied .bar { ... } article { ... } :root > article { ... } } main { style-set: Main; } // main element with the set applied This solution solves two problems: 1. Modular/componentized style definition - same goal as in nesting styles, but without introduction of new syntax constructs. 2. Reduces CSS resolution load. Rules inside the set are scanned only for DOM children that have style set defined. 3. DOM element may have @styleset="url#name" attribute defined - used in components (Web alike components and React alike components)
- ocimbote 4y agoIf syntactic sugar was really just sugar, JS would have sticked to callback functions, and we’d still be inventing abstractions to make our lives easier. Syntactic sugar, sometimes, is the promise of sunnier mornings and that matters.
- scambier 4y ago"For a Linux user, you can already build such a system yourself quite trivially by getting an FTP account, mounting it locally with curlftpfs, and then using SVN or CVS on the mounted filesystem. From Windows or Mac, this FTP account could be accessed through built-in software."
- sirsinsalot 4y agoSolid reference
- tommica 4y agoFor those that do not know what this refers to: https://news.ycombinator.com/item?id=8863 https://news.ycombinator.com/item?id=8863
- bryanrasmussen 4y agounpopular opinion I'm sure from reading everyone here, but to me nesting css is syntactic poison - or maybe syntactic sucrose or something that gives you cancer you use too much of it? Anyway programmers given nesting just do it all the time which ends up leading to stuff like article.news section.preamble h1 and probably a few other selectors after that all nested giving you a wonderful high priority for your style and possible collisions. Then the same guys who made the problem can't figure out the problem so they figure some highlevel nesting is the solution so there won't be any collisions and overriding of styles.
- mkhalil 4y agoI am supportive of this. Ofc, parent selector would still be nice, but I understand the problems solving that performantly. As a highlight, Nested CSS doesn't support nested selectors if they both begin with letters, so the "&" is used as divider. I highly recommend web-dev's check out the last section of the article*: https://webkit.org/blog/13813/try-css-nesting-today-in-safari-technology-preview/#:~:text=But%20what%20if%20you%20have%20this%20unnested%20code%3F https://webkit.org/blog/13813/try-css-nesting-today-in-safar... [*: even though, IMO, in this instance it seems like a hack; nesting CSS styles, while the HTML is nested in the opposite direction seems pretty counterintuitive. but having the tool in your toolbox could be useful for other things.]
- frosted-flakes 4y agoWe have a parent selector. It's called :has(), and Firefox is the only holdout at this point.
- toastal 4y agoYou can enable it with a flag in Firefox though. If only I could enable subgrid with a Blink flag though ha.
- Sesse__ 4y agoThe flag you're looking for is --enable-blink-features=LayoutNGSubgrid, I assume.
- frosted-flakes 4y agoYou can enable :has in Firefox, but it's buggy and still very experimental at this point. Or at least it was a month or so ago.
- romellem 4y agoDo you know about the `:has()` pseudo-selector? It is basically a parent selector, and has decent browser support already! * https://developer.mozilla.org/en-US/docs/Web/CSS/:has https://developer.mozilla.org/en-US/docs/Web/CSS/:has
- pier25 4y agoBetter late than never :) Very happy to see something major like this being adopted.
- KayL 4y agoI wonder if any editor (vscode or plugin) support nested search soon...
- TekMol 4y agoI'm losing track of what CSS can do. Do we have inheritance already? Pseudocode of what I mean: .info { font-size: 8px; } .news extends .info { color: black; } So news are displayed in an 8px black font.
- mock-possum 4y agonope. you've got a couple of options - .info { font-size: 8px; } .news { color: black; } <div class="info news">asdf</div> or maybe .info { font-size: 8px; } .news { color: black; } <div class="news"><p class="info">asdf</p></div> or even .info, .news { font-size: 8px; } .news { color: black; } <div class="news">asdf</div> but you've got to use LESS/SCSS for true 'extends' type functionality. vanilla CSS is more focused on inheritance.
- TekMol 4y agoOut of these, only the last one seems somewhat okish to me. But it would be annoying to add another selector everytime you add a class that uses the rule. If that is all we have, then I will just stick to css variables: :root { --info-font-size: 8px; } .info { font-size: var(--info-font-size); color: grey; } .news { font-size: var(--info-font-size); color: black; }
- mock-possum 4y agoman I can't wait to not need LESS/SCSS anymore. the less I need to compile/transpile before handing stuff off to the browser, the better in my book.
- irrational 4y agoI’m looking forward to the day when we can get back to no compiling/transpiling web development.
- suprfnk 4y agoI'm afraid TypeScript support in browsers is very far away, if it ever happens.
- manmal 4y agoJSDoc type annotations look good though, and TS can work with them: https://www.typescriptlang.org/docs/handbook/jsdoc-supported-types.html https://www.typescriptlang.org/docs/handbook/jsdoc-supported...
- hbn 4y agoThere's not much of a point. It'd just slow movement on Typescript itself. Unless of course fast-moving, transpiled Typescript started being transpiled to browser-acceptable Typescript, i.e. transpiled back enough to where most browsers can parse it. But at that point, why not just do it the way we're currently doing it, targeting JavaScript? Also it'd just make web dev even more confusing for newcomers than it already is. I don't really see an issue with treating JavaScript as something of an "assembly of the browser," in that anyone can make their own language and target it.
- manmal 4y agoI guess minification is still a good idea? Or is this now irrelevant with gzip everywhere?
- progx 4y agoYup. But currently they offer more as variables and nesting. Templates, Subroutines, etc. Value manipulation (like color changes) are possible in css, but complicated to write and read.
- transfire 4y agoCouldn’t `this` just be a reserved keyword instead of `&`? All these symbols, CSS has become so Perly.
- brewdawg 4y agoCouldn't <this> be a custom HTML element? So there'd be a naming clash.
- somishere 4y agoSanity has prevailed! Great work from the WebKit team, leading the way here. Not to mention great solve on the `color: blue` fiasco. Balances an edge-case compromise nicely, and leaves it open to future improvements. Bravo.
- Epskampie 4y agoWhat is the `color: blue` fiasco?
- somishere 4y agoWriting from memory here, please correct as required, but one of the major concerns with scss style syntax was that it was "undesirable" for interpreters to differentiate between tag names and properties due to legacy CSS token-parsing techniques and the performance concerns around "infinite" lookahead ("controversial"). `color` is one example (possibly the only example) of CSS property / tag name overlap which makes the scss style syntax `tag { color:hover { color:blue } }` slightly ambiguous and potentially tricky to parse.
- TabAtkins 4y agoFwiw, while I deeply appreciate WebKit supporting the proposal as well, the editors of the Nesting spec are Googlers and the Chrome impl happened at the same time.
- somishere 4y agoWorth a lot! Thanks for clarifying. You need to give your product manager / blog team a kick :)
- cunningfatalist 4y agoI am not a big fan of nesting. I have yet to see a codebase where nesting makes CSS more readable. Even with BEM, I find it easier to reason about (and debug) the vanilla style. However, I must admit that `&:hover{}` does have a certain appeal. Also, I am very happy that nesting can be done without tooling in the future. It's a feature that many people love.
- jhughes982 4y agoI agree, for some reason my brain sees the non-nested versions of CSS as more readable. Although we seem to be in the minority here. Very open to trying out nesting and perhaps my brain will 'flip' to eventually prefer it.
- kerryoco 4y agoit comes down to the Inspector for me. I've had zero problems thus far right clicking on elements and then clicking on the relevant CSS exposed. I don't think anyone should actually be reading through CSS docs (will admit I'm a solo dev here so got it easy), and I'm afraid this could make the Inspector more confusing. furthermore I suspect a very large % of people do not realize you can actually edit and save your CSS directly with Workspaces.
- onion-soup 4y ago[flagged]
- yladiz 4y agoCan you support saying why it's an anti-pattern rather than just saying something inflammatory?
- d--b 4y agoSo they dropped "@nest"?
- maattdd 4y agoYes @nest is gone
- oliwarner 4y agoIt's great it's here, but isn't everyone and their dog who wants features like this using PostCSS, LESS or SASS? In a build environment that nearly makes this transparent. I use Vite and PostCSS and a bevy of linters, image processing tools, even for CSS-only projects because they're so fast and generally so good at what they do that it'd be silly not to. I used to hodge tools together with Makefiles but Vite in particular has made the setup for all this stupid-simple. I make changes, 100ms later Vite deposits a new, optimised build into my Django static dir.
- iLoveOncall 4y agoThis has benefits even if you use those pre-processors. One I have in mind is smaller CSS file sizes.
- oliwarner 4y agoI can think of a very few, very extreme examples that I've worked on where that might be a registrable amount, but even then, you're only saving on duplicated parent classes/element which would have been taken care of by simple gzip compression. There are [increasingly few] times when it's just nice to just write CSS and I guess unifying nesting will make that nicer, but I don't think there are tangible benefits over "flat" production output.
- deleted 4y ago[deleted]
- meerita 4y agoThat's a valuable addition, but it's unfortunate that it arrived late. These days, functional CSS http://minid.net/2019/04/07/the-css-utilitarian-methodology/ http://minid.net/2019/04/07/the-css-utilitarian-methodology/ is gaining popularity due to its effectiveness in reducing the need for excessive nesting of classes and unwieldy CSS files.
- dgb23 4y agoFunctional/atomic css is great. But there are many use cases for composing and refactoring them into aggregates. Nested css can help you for tgese cases.
- meerita 4y agoThe more you rely on CSS to change the visuals based on situations, the worst to main in the future. It's an option, that's good, but for me it's been years that I don't go back to that anymore.
- lofaszvanitt 4y ago"Everyone wishes CSS nesting could use the same kind of simple syntax that Sass does. That’s impossible" Oh man... let the asteroid come.
- whstl 4y agoThis is a good thing. I'm currently writing a toy "javascript" bundler. I implemented a CSS parser in the past (mostly for linting) and it took me a few hours. Trying to do the same with SCSS made me give up halfway. The test suite was >6000 tests or so and I got up to about 3000 or something, but it gets harder the further up you go. There's lots of other people in Github that are smarter than me and had the same experience, leaving their parser halfway finished. There's a lot of smart stuff in SCSS, and that is perfectly fine for a compile-time tool, but it's not something that's fast enough for a browser, or simple enough that can be added quickly to their current parsers.
- hollowturtle 4y agoThis won’t kill Sass/scss. Compilers will still be useful for many reasons, I see those compilers targeting new standards instead. Also, bummer that nested rules made it but <style scoped> was removed. The only viable option for me today to keep a maintainable css code base is to use a css in js solution and a compiler. In fact I don’t see why all this excitement for native features, if all you need could be just a capable compiler(bundling, minification, optimization, dead code elimination etc.)
- brewdawg 4y ago> Because of limitations in browser parsing engines... I'm happy about this feature, but they don't really elaborate on what these "limitations" are, except a passing reference later on to "making the parsing engine slower". Anyone know what the issue is exactly? Why can't they implement it the other way without making the parsing engine slower?
- kerkeslager 4y agoCan someone explain why parsers can't handle nested selectors which don't start with a symbol? I've written plenty of parsers (recursive descent, packrat, Pratt, and using generators) and not a single one would have any trouble parsing something like: html { body:has(p) { width: 1000px; } } The only thing I can think of is that they are trying to avoid a lookahead, i.e. you have selectors like "body:has(p) {" which initially look like they could be setting a "body" attribute to the value "has" until you reach the "(". But these lookaheads aren't hard to implement in practice. There are performance issues if the lookahead has to go too deep, but CSS developers can use the & in those cases as an optimization, and you could limit lookahead depth to something like 256 (which would handle the vast majority of non-malicious use cases). Perhaps the lookahead has a lot more drastic effect than I'm expecting on performance for short lookaheads, but I'd like to at least see some profiling of that, as it seems to me like this possibility was discarded without much consideration or explanation (it wasn't even included in the poll). There's also another way to do this without lookaheads at all, by building up a structure for each potential path and then discarding the one that doesn't complete (I think this is basically a DFA but it's been a while since I read literature on this so I'm forgetting the terminology). This would probably avoid the performance issues but also probably be a larger departure from the current implementation of the parsers.
- maattdd 4y agoIndeed, the reason is simply to keep the current look-ahead(1) for the CSS syntax. If you allow nested rules with selector list which doesn't start with a symbol, you need (in theory) an unbounded look-ahead. However, the current spec has been written in a way that it doesn't prevent removing this restriction in the future. But the CSSWG would prefer to have some real world profiling data to know the actual performance cost of removing this restriction.
- chrismorgan 4y agoSee https://github.com/w3c/csswg-drafts/issues/7961 https://github.com/w3c/csswg-drafts/issues/7961, which details some of the problems, including genuine and currently irreconcilable ambiguities, and goes into attempting to make it work by adding convoluted and complex rules and arbitrary lookahead in a way that I really strongly hope gets nixed because it’s awful. (And they’re really only trying to do this because they resolved to make & optional in #7834, which I think was where things started going wrong.)
- jefftk 4y agoNot implemented in Firefox yet, but they like it: https://github.com/mozilla/standards-positions/issues/695 https://github.com/mozilla/standards-positions/issues/695 They're tracking work in https://bugzilla.mozilla.org/show_bug.cgi?id=1648037 https://bugzilla.mozilla.org/show_bug.cgi?id=1648037
- adamwathan 4y agoOne thing worth noting is that & substitutes for `:is(...)` in spirit under the hood, which means there are some significant behavior differences between native CSS nesting and Sass. Here's one: .foo .bar { .baz & { color: red; } } In Sass, that would compile to: .baz .foo .bar { color: red; } With native nesting, it effectively compiles to: .baz :is(.foo .bar) { color: red; } The Sass version matches this DOM structure: <div class="baz"> <div class="foo"> <div class="bar"> ... But the native version matches all of these structures: <div class="baz"> <div class="foo"> <div class="bar"> ... <div class="foo"> <div class="baz"> <div class="bar"> ... <div class="foo baz"> <div class="bar"> ... Not a criticism at all (the `:is(...)` behavior is a very useful and welcome enhancement to CSS) but a notable difference worth understanding coming from Sass.
- DrBenCarson 4y agoAgree important to note the difference but I personally prefer the nested CSS behavior. Much more sensible to use `&` as a logical operator
- TabAtkins 4y agoNotably, this is identical to the behavior you get from @scope's nesting, and from passing a complex selector to an `el.querySelector()`. (We discussed adopting Sass's behavior in <https://github.com/w3c/csswg-drafts/issues/8310#issuecomment-1397648398 https://github.com/w3c/csswg-drafts/issues/8310#issuecomment...> but ultimately dropped it.)
- __ryan__ 4y agoI’ll criticize it. I recognize this is a preview and I desperately hope this implementation isn’t kept around and treated as a quirk. This implementation is extremely unintuitive given their explanation of the expected behavior of CSS Nesting and the & symbol. To quote: The & signals to the browser “this is where I want the selector from outside this nest to go”. Their explanation and the actual implementation result in a majorly different CSS selector. The implemented functionality, however useful, makes no sense as a default if one can explicitly use :is to achieve this behavior like below. .foo .bar { .baz :is(&) { } } The default should behave like they claim it does; simply replace & with the “outside” selector.
- dang 4y agoRelated: Help choose the syntax for CSS Nesting - https://news.ycombinator.com/item?id=34006622 https://news.ycombinator.com/item?id=34006622 - Dec 2022 (159 comments) Updated CSS Nesting Syntax to Avoid Common Copy-and-Paste Errors - https://news.ycombinator.com/item?id=33537539 https://news.ycombinator.com/item?id=33537539 - Nov 2022 (1 comment) CSS Nesting - https://news.ycombinator.com/item?id=33424361 https://news.ycombinator.com/item?id=33424361 - Nov 2022 (2 comments) Help pick a syntax for CSS nesting - https://news.ycombinator.com/item?id=32248419 https://news.ycombinator.com/item?id=32248419 - July 2022 (240 comments) CSS Nesting Module - https://news.ycombinator.com/item?id=28375596 https://news.ycombinator.com/item?id=28375596 - Sept 2021 (71 comments) CSS Nesting Module - W3C Editor’s Draft - https://news.ycombinator.com/item?id=27684332 https://news.ycombinator.com/item?id=27684332 - June 2021 (1 comment) You Probably Shouldn't Be Nesting Your CSS - https://news.ycombinator.com/item?id=6583109 https://news.ycombinator.com/item?id=6583109 - Oct 2013 (1 comment) WebKit to get CSS variables, mixins, nesting? - https://news.ycombinator.com/item?id=2111510 https://news.ycombinator.com/item?id=2111510 - Jan 2011 (6 comments)
- TAKEMYMONEY 4y agoThis syntax matches the CSS Working Group's recommendations, is that correct? > "starting the nested selector with an identifier is invalid" https://www.w3.org/TR/css-nesting-1/#example-34e8e94f https://www.w3.org/TR/css-nesting-1/#example-34e8e94f
- m3kw9 4y agoWhat would this mean for the type of website designs we could see?
- zestyping 4y agoThe leading "&" should be required. All of these questions and quandaries only exist because the "&" is optional. If it were simply required, there would be no ambiguity to humans or to parsers.
- devmunchies 4y agoAnother benefit I'm not seeing is that sass/less/minifiers can now target this new native nesting for the output, which would reduce the overall byte size of the output. So you don't need to use nesting in your code if you don't want to, but can still take advantage for smaller minified css files using a transpiler.
- v3ss0n 4y agoCss is one hell of a spaghetti mess, why need nested css?