10 ms·
CSS now has an if() conditional function
- aanthonymax 11mo agoThis support has appeared in the new W3C specification.
- tantalor 11mo agohttps://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Values/if https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/V...
- themafia 11mo agoIt's a great way to make conditional styles without having to use JavaScript; however, having used JS for years to make theme color and icon sets that rely on CSS properties, I'm not sure I particularly like this method. I feel like you have to smear a lot of logic across your CSS whereas with JS you can reduce your theme to a data structure and just have a simple function to setup all the CSS variables based on that. Am I just an old man?
- kevin_thibedeau 11mo agoJust use SCSS to smear the logic across CSS automatically.
- functionmouse 11mo agoI like making static informational pages and don't know the first thing about JavaScript, so this could be handy for me.
- mmis1000 11mo agoJavascript always suffer from FOUC problem though (Unless it's server side). Although the if() css function seems to just be syntax suger of standard @media query. So it doesn't really add anything to solve existing problems. Edited: It seems it can also be toggled from css variable? So it might actually fix some existing problems.
- mikestorrent 11mo agoHow hard would it be to have a response header that tells the browser "don't display anything at all until we ask you to from JS when we're ready"? Considering the kinds of crap that have been done with headers...
- coke12 11mo agoMany sites do something like that in practice. The problem is the extra 500ms of parse+eval time for your JS bundle influences user behavior a lot on the margin, so it’s better to not force the user to wait.
- mmis1000 11mo agoPractically only cordova does these for now. But it's a native app so of course it can do whatever it want.
- Tajnymag 11mo agoWould it be enough to have <body> hidden using an inline style in the initial html response and when everything is loaded, one would remove the style using javascript?
- account42 11mo agoHow hard would it be to use JS for progressive enhancement instead making your website depend on it to display simple text and images.
- bawolff 11mo agoThe primary goal is to just have a more concise way to do @media queries. Its not intended as a replacement for most uses of JS
- 6031769 11mo agoIf we've learned anything from the history of CSS, JS and the semantic web it is that 99% of the time a feature will be used in ways that were not intended. There is no reason to suppose that this will be any different.
- sublinear 11mo agoYou have to consider why, and the answer was often "there's no other way". The paths of least resistance on the web are now very different. These features were not delayed due to implementation details, but a deliberate shepherding of the standards. The most powerful features were saved for later and even still this is scoped to media queries, etc. only.
- Denote6737 11mo agoGod forbid we use html5
- assimpleaspossi 11mo agoThere is no HTML5 other than a buzzword: https://html.spec.whatwg.org/dev/introduction.html#is-this-html5 https://html.spec.whatwg.org/dev/introduction.html#is-this-h...?
- pie_flavor 11mo agoYou're pulling the old man card on CSS-in-JS? Putting your style logic in CSS is what CSS is for, CSS-in-JS is an annoying hack to make React work. What this is replacing is SCSS.
- masswerk 11mo agoWell, historically, styles were first in JS (JS StyleSheets in Netscape 4.0) and were pulled out into CSS. – This is an old man card! ;-)
- stevefan1999 11mo agoWith the inclusion of branches, is it possible to say that CSS is now even more Turing-Complete? Now we just need to find ways to do recursion/targeted jumps so that it is finally recursive-enumerable
- ImHereToVote 11mo agoDoom on CSS when?
- anthk 11mo agoYou can maybe run ZMachine games (not just Zork, there are several better games there) under zmachine.ps, written in PostScript. And, maybe, in a TTF font.
- cluckindan 11mo agoDon’t apply programming language mental models onto CSS features. CSS if() probably just merges one of two single-property RuleSets onto the parent RuleSet depending on the condition, which has nothing to do with branching, as there is no execution flow to branch.
- culi 11mo agoFar from being ready when only one major browser supports it. If you want this, you should vote for it to be focused on for interop-2026 https://github.com/web-platform-tests/interop/issues https://github.com/web-platform-tests/interop/issues Right now, the leading CSS proposals are `@container style()`, `corner-shape` and `break-after` https://foolip.github.io/interop-reactions/ https://foolip.github.io/interop-reactions/
- hdjrudni 11mo agoYeesh.. I've definitely tried using break-after and being disappointed it didn't work properly. The amount of hoops I had to jump through to get things to print properly on paper...
- fuzzfactor 11mo ago>The amount of hoops I had to jump through to get things to print properly on paper... Anybody know how that compares to Report Definition Language? https://learn.microsoft.com/en-us/sql/reporting-services/reports/report-definition-language-ssrs https://learn.microsoft.com/en-us/sql/reporting-services/rep... Seems like an awfully scattered shitshow just to arrive at a typical "What You See Is Not What You Get" result. And this one is made for printouts.
- culi 11mo agoAgreed. This has come up multiple times during my job. It's gotten to the point where we had a microservice running that spun up selenium and printed the dom and then sent that pdf back to the front-end all just to make consistent print outputs. I've read tech blogs of others doing just that too so it's not uncommon. Unfortunately the test set of wpt does not have the capability to cover printed matter so relief isn't coming any time soon
- StoneAndSky 11mo agoThe People have spoken, and they want squircles.
- zb3 11mo agoNot supported in Firefox and Safari. Also it seems most people forget that the more bloated the web platform is, the more resources are needed to develop and maintain a web browser engine.. Chromium is open-source, but it's already expensive to maintain a fork or even rebuild it..
- zeroCalories 11mo ago[flagged]
- zb3 11mo ago> How did this happen? That's pretty simple - Google has poured tons of money into Chrome and Mozilla. Google is not a charity so this was a strategic investment. > You should go over to the CSS working group and let them know That wouldn't work, money is what ultimately matters there.
- zeroCalories 11mo ago[flagged]
- singpolyma3 11mo agolol. What other browser vendors? Whatwg is just google is a trench coat. Edge is chrome. Firefox is funded by Google. So I guess apple who's main contribution is being years behind and having half their stuff be broken
- zeroCalories 11mo agoThere's this really cool site where you can see how well supported a feature is: https://caniuse.com/?search=if https://caniuse.com/?search=if If Google controls everything, why is if() only supported on 59% traffic? Do you think any serious company will let their site break on 40% of clients? Do you think Apple's opinion is unimportant?
- xnx 11mo agoIf we could do it over, knowing that we'd eventually get to this point, would https://en.wikipedia.org/wiki/JavaScript_Style_Sheets https://en.wikipedia.org/wiki/JavaScript_Style_Sheets have been the better path?
- runarberg 11mo agoProbably not. There is a lot of optimizations browsers do to make the stylesheets super fast[1], and I think quite a few of those rely on CSS not being Turing complete. 1: https://hacks.mozilla.org/2017/08/inside-a-super-fast-css-engine-quantum-css-aka-stylo/ https://hacks.mozilla.org/2017/08/inside-a-super-fast-css-en...
- Sesse__ 11mo agoCSS is Turing complete :-) You can find pure-CSS implementations of Game of Life, for instance.
- cluckindan 11mo agoI don’t think that’s true, unless you count hardcoding the state evolution into CSS variables, one var per cell per step.
- runarberg 11mo agoThe implementations I have seen rely on the inclusion of HTML form elements, and a manual step to update the state. So in that sense CSS + HTML + User Interaction is Turing complete. But that is a different language then CSS, even if a part of that language happens to be written in CSS.
- Sesse__ 11mo agohttps://propjockey.github.io/css-conways-game-of-life/infinite-edition/ https://propjockey.github.io/css-conways-game-of-life/infini... as an example. No user interaction except to start.
- mr_windfrog 11mo agoI'm not really sure I understand this. How is the new if() conditional function different from using @media (width ...) when adapting layouts to browser width?
- bawolff 11mo agoIts basically the same, just more convinent syntax. I think if can also do string equality on variable values, which is a bit new but also niche. The main point is just to do @media but inside a property decleration.
- michaelcampbell 11mo agoIf I'm reading it right, the if condition/predicate can check more things than @media() can.
- bingemaker 11mo agoI'm not sure turning CSS into a full blown language is a good idea. With all the cascading in place, it is already a bit hard to determine why certain styles are applied. Now with this, we will be spending more brain cells debugging CSS issues.
- lmm 11mo agoOn the contrary, a lot of the reason CSS is confusing is because it's full of insane hacks people have to do to get the behaviour they want. A straight-up if statement is much simpler than many of the horrors I've seen.
- squeefers 11mo ago[dead]
- alwillis 11mo ago>On the contrary, a lot of the reason CSS is confusing is because it's full of insane hacks people have to do to get the behaviour they want. CSS is confusing because the vast majority of web developers never learned it properly. Many developers won't learn any "new" CSS (like CSS Grid which shipped in all browsers in 2017) beyond the hacks they learned in the '90s and early 2000's. That's not the fault of CSS.
- lmm 11mo ago> CSS is confusing because the vast majority of web developers never learned it properly. Many developers won't learn any "new" CSS (like CSS Grid which shipped in all browsers in 2017) beyond the hacks they learned in the '90s and early 2000's. Disagree. The newer stuff is, if anything, more confusing. The old stuff, awful as it was, at least had a consistent model.
- alwillis 11mo ago> Disagree. The newer stuff is, if anything, more confusing. The old stuff, awful as it was, at least had a consistent model. With the "old stuff", we didn't a layout model or an alignment model. Everything required float and positioning hacks to do things they weren't designed to do. There's no logical way that was "better." There were several different grid systems, all mostly incompatible with each other, which were required to do anything interesting. Many layouts that are common today were impossible to do with just HTML & CSS back in '90s and 2000's. Capabilities that almost all developers had to reach for a framework Bootstrap or Foundation for are built-in to CSS today. Or lots of JavaScript.
- darig 11mo ago[dead]
- silverwind 11mo agoThis is missing a "if variable equals" imho. Right now it seems like pure syntactic sugar for a media query.
- ramesh31 11mo ago>This is missing a "if variable equals" imho. This is exactly what it does not need. SASS style conditional CSS is a complete nightmare to maintain. The declarative nature is one of its greatest strengths.
- bawolff 11mo agoDid you guys read the docs? It literally does have this albeit the syntax is a bit odd: if(style(--foo: bar): baz) Is how you test if variable --foo is equal to "bar" See https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Values/if https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/V...
- foreigner 11mo agoCan these be used inside inline style attributes?
- zuhsetaqi 11mo agoIt's a working draft and only available in Chromium ...
- zkmon 11mo agoGive it enough time, every declarative language becomes a programming language. This is happening with all config files, markup languages, data formats. The distinction between code, config and data is being erased. Everything is a soup now. Data is application, configuration is code. Code is an intermediate, volatile thing that is generated on the fly and executed in the temporary lambda containers.
- thwarted 11mo agoWe can blame von Neumann (et al) and his infernal architecture, where memory stores both instructions and data.
- account42 11mo agoNot really, most of these configuration as code systems are not executed directly on the CPU but rather interpreted in which case a separate data-only memory would not stop anyone.
- josefx 11mo agoYou can blame whoever invented the word "if", as soon as you can branch based on data you can just write an interpreter that turns data into instructions, no matter the architecture.
- amelius 11mo agoYou need more than if for Turing completeness though.
- alexdns 11mo agoCorrect. You need at least 2 ifs.
- spooky_deep 11mo agoYou need unbounded recursion no?
- EmilStenstrom 11mo agoHere is a much better link to how it works: https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Values/if https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/V...
- cubefox 11mo agopadding: 1em; padding: if(style(--size: "2xl"): 1em; else: 0.25em); > Note: Remember to include the else condition. In if()-supporting browsers, if no else value were included and --size was not equal to "2xl", the padding would be set to initial. This is counterintuitive. You would expect the above falls back to "1em" (from "padding: 1em;") when "else" is not specified. Instead, omitting "else" apparently means "else: initial".
- kaelwd 11mo agoThat's the same as regular css variables unfortunately padding: 1em; padding: var(--padding); With no fallback value that resolves to padding: unset if the variable is not defined. The only ways I know of to work around this are style queries: padding: 1em; @container style(--padding) { padding: var(--padding); } Or cascade layers: @layer base { padding: 1em; } @layer override { padding: var(--padding, revert-layer); }
- nottorp 11mo agoSo we were looking in the wrong direction for AGI!
- nottorp 11mo agoReplying to myself (hey, I like myself and I'd like to have a conversation with me): CSS doesn't have it right? Just Chrome. Considering how all kinds of "experts" have started to make web sites that only work fine in Chrome [1], this is not exactly a useful new feature, more like embrace and extend... [1] Orange Romania, when will I be able to download my invoices again in Firefox?
- jeroenhd 11mo agoIt's in the draft spec for the CSS Values and Units Module Level 5 (https://drafts.csswg.org/css-values-5/#if-notation https://drafts.csswg.org/css-values-5/#if-notation) I don't see Mozilla's or WebKit's positions anywhere, so this is a Chromium-only feature for now.
- JimDabell 11mo agoCuriously, Can I Use says: > All major browser engines are working on implementing this spec. However their official positions are absent: https://github.com/mozilla/standards-positions/issues/1167 https://github.com/mozilla/standards-positions/issues/1167 https://github.com/WebKit/standards-positions/issues/453 https://github.com/WebKit/standards-positions/issues/453 And Firefox’s bug for implementing it has no activity: https://bugzilla.mozilla.org/show_bug.cgi?id=1981485 https://bugzilla.mozilla.org/show_bug.cgi?id=1981485 And Can I Use’s underlying data doesn’t have this note: https://github.com/Fyrd/caniuse/blob/fedfb067aceccb2a5edadcc8143a8c5be509a006/features-json/css-if.json#L715 https://github.com/Fyrd/caniuse/blob/fedfb067aceccb2a5edadcc... So it’s unclear why the Can I Use website is saying that everybody is working on it.
- nottorp 11mo agoMaybe the site is "AI" generated now.
- Incipient 11mo agoAs long as css remains "so fast it's free" then I'm mostly happy with that - I use css without thinking about optimisations, and I like it like that!
- Sesse__ 11mo agoYou can certainly write slow CSS, and people do :-) JavaScript typically takes up more of the CPU time overall, though.
- cryptonym 11mo agoIt's not free at all. You can profile it with debug tools and find the most expensive selectors to refactor them. You can also write CSS animations that impacts performance/user experience, this can also be profiled. Sorry but if you use advanced feature and especially on a big DOM, you have to think about optimisations.
- mmis1000 11mo agoWell, you can actually write slow css if you make real deep nested flex container. And it's not even too rare. You can actually find such example in yhe wild. The spec of flex layout requires it to layout its child elements several times to compute actual layout. Make it deep and nested without proper constrains will results in n*n*n*n… layout computations and bring down the browser on resize.
- cluckindan 11mo agoIt’s not even that hard. Use flex for layout and you can instantly see how slow reflow becomes when resizing the window.
- jsmailes 11mo agoIf I'm reading this correctly, Opera added support in an earlier version then took it away again. Any idea why they might have done it? Maybe a browser engine change under the hood?
- tanin 11mo agoNice. I've built desktop apps in a few other frameworks e.g. Java Swing, JavaFX, JetBrains Compose, SwiftUI, QT. Nothing is as easy as JS/HTML/CSS. I've realized that the main reason is its robust capabilities e.g rich auto-layouting/positioning capabilities. Meanwhile in other UI frameworks, you either don't do it or you draw the damn things yourself lol. So, most of the times I'd just not do it. Adding if is great. It would reduce the need for JS a bit more, which would make the code more maintainable.
- Aardwolf 11mo agoCan it already vertically and horizontally center unknown-beforehand-length multi-line text in a single html element, just like non-CSS table cells could already in 1995?
- _jzlw 11mo agoalign-content: center; (supported on block elements since sometime last year)
- Aardwolf 11mo agoThanks, seems to work at first sight in combination with text-align for the horizontal alignment! That means I may finally not need line-height or multi-element tricks for this anymore Interesting that this is finally there since a year! I wonder what made them decide to support it finally, since CSS's creation in 1996. A button never looks professional if the text in it isn't centered, this was a really needed feature and I still can't understand why it took that long Edit: it does seem worrying that for me this property vertically centers but not horizontally while the description of it doesn't say vertical but is: "The items are packed flush to each other in the center of the alignment container along the cross axis."
- _jzlw 11mo ago> The items are packed flush to each other in the center of the alignment container along the cross axis You're right, the entire Values section seems to still be worded exclusively for flexboxes. The description at the top adds "or a grid or block-level element's block axis".
- JimDabell 11mo ago> Can it already vertically and horizontally center unknown-beforehand-length multi-line text in a single html element, just like non-CSS table cells could already in 1995? Non-CSS table cells have never been able to do that – you need a wrapping <table> at minimum for browsers to render it how you want, a <tr> for it to be valid HTML, and <tbody> comes along for the ride as well as an implied element. So that’s four elements if you want to centre vertically with <td> or <th>. If you wait until the year 2000, then you can get that down to three elements by switching from HTML to XHTML because <tbody> is no longer implied in XHTML. CSS, on the other hand, has been able to do what you want since 1998 (CSS 2) with only two elements: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> <title>.</title> <style type="text/css"> html, body { height: 100%; } .outer { display: table; width: 100%; height: 100%; } .inner { display: table-cell; vertical-align: middle; text-align: center; } </style> <div class="outer"> <div class="inner"> Test<br> Test<br> Test<br> Test<br> Test<br> Test </div> </div> (I’m using a <style> element here for clarity, but you can do the same thing with style attributes.) https://www.w3.org/TR/1998/REC-CSS2-19980512/ https://www.w3.org/TR/1998/REC-CSS2-19980512/
- chipx86 11mo agoI'm pretty happy to see this, as conditionals can really help keep code manageable when trying to define CSS variables or other properties based on combinations of light mode, dark mode, high-contrast, contextual state in a document or component, etc. if() isn't the only way to do this, though. We've been using a technique in Review Board that's roughly equivalent to if(), but compatible with any browser supporting CSS variables. It involves: 1. Defining your conditions based on selectors/media queries (say, a dark mode media selector, light mode, some data attribute on a component, etc.). 2. Defining a set of related CSS variables within those to mark which are TRUE (using an empty value) and which are FALSE (`initial`). 3. Using those CSS variables with fallback syntax to choose a value based on which is TRUE (using `var(--my-state, fallback)` syntax). I wrote about it all here, with a handful of working examples: https://chipx86.blog/2025/08/08/what-if-using-conditional-css-variables/ https://chipx86.blog/2025/08/08/what-if-using-conditional-cs... Also includes a comparison between if() and this approach, so you can more easily get a sense of how they both work.
- bradly 11mo agoI recently implemented dark/light mode for the first time and was really surprised to find that in order to add a toggle I had to duplicate a both of vars/styles and use JavaScript. I'm looking forward to not having to deal with that cruft in the future.
- hebelehubele 11mo agoYou can do without javascript. Checkbox `:checked` + `label` trick for toggling states still works. See: https://codepen.io/abdus/pen/bNpQqXv https://codepen.io/abdus/pen/bNpQqXv
- bradly 11mo agoThanks, I’ll check this out!
- hebelehubele 11mo ago
- manucardoen 11mo agoSomewhere, someone has just started porting Doom to CSS.
- layer8 11mo agoI guess we can now write Excel in CSS.
- fuzzfactor 11mo agoInteresting, a few organizations can (very) carefully craft their own LOB software over the number of years it can take to fully free themselves from Excel. And then realize the intended advantage for years to come. At the same time over a period of years the web approach is to make the whole thing more like a bunch of interlocked Excels, more so than it already was before. Does that mean any resulting disadvantage during following years is intentional? Any more than huge orgs grew to depend on Excel, one physical desktop at a time since that was the only thing in common among all those diverse desk owners that would do the job, plus it was the first thing to come along to fill that niche.
- marcinignac 11mo agoProposed title change "Chrome now has an if() conditional function in CSS"
- phplovesong 11mo agoNow we just need a while loop to make it turing complete.
- nake89 11mo agoLoops would be nice. To make cool fireworks animations with CSS, you basically need to use SCSS to CSS compiler: https://codepen.io/hmaw/pen/qBEMLxV https://codepen.io/hmaw/pen/qBEMLxV
- qwertytyyuu 11mo agooh no, this is going to cause abomninations,
- neuralkoi 11mo agoQuick, someone get DOOM running on CSS!
- James_K 11mo agoHow about giving me the option to use variables in media queries?
- sethops1 11mo agoYeah this one seems like such low hanging fruit and would be a great convenience.
- deleted 11mo ago[deleted]
- dsnr 11mo agoNext I want to run WASM inside CSS. W3C, please don’t disappoint.
- markaroo 11mo agoif (it's fast) { i'm excited }
- rcarmo 11mo agoIs it Turing-complete yet? Seems close, but I've lost track.
- bmn__ 11mo agohttps://gwern.net/turing-complete#:~:text=CSS https://gwern.net/turing-complete#:~:text=CSS
- hasbot 11mo agoHuh. 35 year ago I was the sole maintainer of an in-house SQL-like database query language. The application was transforming relational data into a more concise and efficient format for use in an embedded application (AT&T 5ESS digital switch). All the mapping was done in this SQL-like language. One of my power users mentioned the difficulty they had in actually changing logic based on the values in the database. For example, to perform different logic based on whether a column was a 1 or a 2, they'd have to write two querys: one for 1 and another for 2. Possible, sure, but not very clean or efficient. To address this, I implemented an if() function.
- paxcoder 11mo ago[dead]
- shevy-java 11mo agoThey want to turn it into a programming language ... :/
- zombot 11mo agoHow long before CSS can run Doom?
- anthk 11mo agoNice, does it make turing complete? If so, another crap to block under Dillo. That's what happens when you design a language by comitee (C++, JS) and try to do stuff in the web for a platform made to share static documents. Just look at what kind of disasters the users faced with Office macros.
- trollbridge 11mo agoOne of the nice things working in vite is realising, “hey, this config file is just {Java,Type}Script”.
- vaylian 11mo agoNot supported in Firefox
- Pwntastic 11mo agojust a meta note that the submitter, aanthonymax, likely only posted this to launder karma to avoid being shadowed for spamming their github project. a quick look at their post history shows that they only post links to their github project and then occasionally extremely low effort random mdn or other useless links to try to balance our their account. their previous account was shadowed for basically the same thing
- matheusmoreira 11mo agoThis stuff makes me paranoid about posting my projects here and everywhere. Don't want to be seen as advertising my code...
- Pwntastic 11mo agoit's one thing to openly self-promote your project, and another thing to have created multiple accounts that spam links to your project on a weekly basis
- moritzwarhier 11mo agoI'm kind of thankful not having to work with people trying to be clever in CSS anymore (especially "clever" backend developers). And I used to defend and evangelize taking HTML&CSS seriously in my previous roles, which I'd still do! But as much as I have longed for features like these in the past (also: :has(), container queries, custom properties...), I dislike this. I found CSS grid disappointing for most use cases. I think :has() is a terrible idea, except for quick hacks. I still think container queries and custom properties are good. But, oh well, old man yelling at cloud.
- mxey 11mo agoHaven’t seen this mentioned yet, but this means you can do media queries in inline styles, right?