12 ms·
The Zen of Just Writing CSS
- jlebrech 9y agowasn't this all possible with tables and iframes. we even had IDEs back in the day that compiled wysiwyg into that code. we're repeating everything but just in a prettier way.
- aethant 9y agoPure zen is vanilla-css.com
- ergothus 9y agoTL;DR: People love to hate CSS, but it's the reality. People have various solutions to deal with the major problems with CSS (i.e. cascading global styles mean impact of any is unpredictable) but recently people have begun tying the CSS to the particular HTML collection it applies to, and the author likes that and points out some particular implementations he likes (I'm assuming "Rich" is/identifies as male).
- rich_harris 9y agocorrect — he/his/him. Yes, exactly, the key here is that CSS is meaningless except in the context of markup: if you can statically analyze the two things together, good things happen.
- madeofpalk 9y agoScoped CSS really is the most forward-thinking CSS IMHO. It's 'plain' enough to be adopted into most workflows and it doesn't really stray very far from the original CSS language.
- braindouche 9y agoScoping CSS is great, you can do static analysis, idiot-proof just-in-time stylesheet loading, and when done correctly it eliminates a lot of specificity issues. It doesn't scale well though. Eventually you develop http-call bloat, and unless your CSS is written by a single and very devoted person, consistency becomes nearly impossible to maintain. Visual consistency begs for DRY CSS, and DRY CSS tends to bend back towards single global stylesheets.
- martin_drapeau 9y agoTotally agree with you. The style of a site or app is global after all. Consistency is key.
- rich_harris 9y agoThe http call bloat is a by-product of how your build process works though — if your CSS lives in your components then you can easily bundle it just like you bundle your JavaScript. The ability to lazy-load individual components and their styles if you wish is a feature, not a bug. It's fine to still have a (preferably fairly small!) global stylesheet that covers fonts, colours and so on. The key is to avoid your components potentially clobbering each other, which is what SFCs accomplish.
- madeofpalk 9y agoI don't think so. In fact, 'scale' is specifically when scoped CSS is its strongest. It allows you break things out and move quicker and develop easier to maintain styles. 1) http-call bloat is mitigated by a built process (which you would probably already have to use if you're using a Scoped CSS method like CSS Modules. 2) Visual consistency and DRY aren't affected. Think about it like regular code - when we want to repeat a unit of code we break it out into a seperate compassable function. We can do the same thing in CSS Modules with composes. You could also (carefully) introduce a preprocessor like LESS/SASS/Stylus/etc for variables and mixins and what not.
- deleted 9y ago[deleted]
- swlkr 9y agoI was using CSS in JS or CSS scoped to components, but what really solved my problems was tachyons
- joe_fro 9y agonot familiar with tachyons and just did a cursory look at it, what about tachyons really solved your problem?
- swlkr 9y agoThe problem of locally scoped CSS vs shared styles across components sometimes. With tachyons I still wrap up styles in components but I also get globally scoped CSS for consistency with fonts/spacing.
- noreplynorepl 9y agooh god, another perfectionist complaining about globals... so predictable. author, the problem is YOU and not css.
- deleted 9y ago[deleted]
- barryhoodlum 9y agoHow do you re-use CSS across components?
- rich_harris 9y agoThat's one of the unresolved questions. A couple of possible solutions: * have a small global stylesheet with styles that are common to many components * put the styles in a mutual parent component and opt-in to the cascade with the :global(...) modifier (from CSS modules) * you don't. This is often the answer I prefer. DRY code is less flexible, and I've often found it far better to have some duplication 5 minutes before I ship rather than be desperately trying to change some CSS on this component without also affecting those components But yes, this is an area we still need to work on.
- madeofpalk 9y agoCSS Modules has composes https://github.com/css-modules/css-modules#composition https://github.com/css-modules/css-modules#composition
- dlbucci 9y agoI like the simplicity provided by scoped CSS, and I tend to name classes in a way that essentially accomplishes scoping. However, there's this nagging feeling at the back of my mind that if every component in your app has its own stylesheet, your style is maybe not consistent? It just seems like the ideal website with a consistent and good UI design should be able to have a single stylesheet (probably written in Stylus/SASS). I don't know if this ever happens in practice, but it's just something I think about. Less on-topic, I feel like the title of this article is wrong: you're not "Just Writing CSS" if you're writing scoped CSS, which requires some sort of build system.
- abritinthebay 9y agoI’m writing scoped CSS in SASS - I’d postulate that that is the maximum you should require (and most sass systems will have a way build on request to your server).
- rich_harris 9y agoI debated whether to title it something else for that exact reason. But I went with 'just writing CSS' because the code you're writing is just CSS, with all the benefits it entails — it's basically just like writing JS inside an IIFE rather than polluting the global namespace. You make a good point about consistency. Personally I'll often have a small global stylesheet that implements basic typography/colour/etc rules — it's more important to ensure that your component styles don't leak out than avoiding global styles leaking in, in my experience.
- monfera 9y agoAn example may be, graphic designer shop gets a contract to update the company 'style guide'. It gets done and there are a lot changes that are cross-cutting w.r.t. components, starting with fonts, borders, margins, border styling etc. Also, what's not fully clear to me, what if - as usually is the case - the components are nested? Changing eg. font in the outer component would leave inner components fully intact? A side note, I'm wondering how the Svelte approach relates to `isolation` in cycle.js https://github.com/cyclejs/cyclejs/issues/259 https://github.com/cyclejs/cyclejs/issues/259 -
- ravenstine 9y agoHere's how I generally deal with CSS: * As the author of that article was talking about, I keep as much CSS scoped to the component level as possible. * Any layout-oriented styling(how a component is positioned and sized on a given page) is separated into its own style sheet per page. That way how a page is laid out is separated from how a particular component looks & behaves. * To deal with the lack of container/element queries, a big roadblock in making components truly reusable, a component style sheet exposes Sass mixins that represent how the component looks at different sizes. The layout CSS for a given page, as mentioned in the last bullet point, includes these mixins at different media query breakpoints. The advantage to this is that the layout can manipulate a component at different breakpoints to create responsiveness without needing to have any knowledge of a component's internal workings. An example of my third point is a component I'm currently working on right now called `incidents-grid`, which is merely a grid of items. The `components/incidents-grid.sass` stylesheet has mixins called `incidents-grid--xl`, `incidents-grid--lg`, `incidents-grid--med`, `incidents-grid--sm`, `incidents-grid--xs`. Other components follow the same convention. For my page, I have a `layout/index.sass` to deal with how I lay out my components on the page. At different media query breakpoints, I will include the incidents-grid mixins to change how the component looks at different sizes; at different sizes, this component may show or not show a thumbnail, or show smaller icons, or no icons, or omit some information. The layout can make these things appear/disapper at different screen sizes without a bunch of CSS specific to the component saying things like `.incidents-grid__thumbnail {display: none}`. Rather, my layout stylesheet can say something like `#l-index__incidents-grid { @include incidents-grid--sm }` in a media query to accomplish the same thing. Granted, this can't be done with plain CSS without some JavaScript. But I've found being able to separate layout CSS from pure styling CSS, as well as abstracting the internal workings of components with mixins, to be a very sane approach.
- err4nt 9y agoFor element/container queries I've written a few plugins: https://docs.google.com/spreadsheets/d/1erAKZq0p6dH3LjtU01hj2PlZH7tZxbGxFUl5jn-V_Hg/edit?usp=sharing https://docs.google.com/spreadsheets/d/1erAKZq0p6dH3LjtU01hj... Ultimately it's something you can DIY in ~30 lines of JavaScript, and over the weekend (just for fun, just to see how far back the ideas worked) I got it running in IE8, IE7, and even IE6 - so it's definitely something you can use today! https://twitter.com/innovati/status/903998563738415104 https://twitter.com/innovati/status/903998563738415104
- s73ver_ 9y agoSo, as someone who currently has no background in web stuff, but is leaning that way, should I be paying a lot of attention to this, or put it on the shelf for now? How does this fit in or compare to Less or Sass?
- jordanlev 9y agoThe article is primarily talking about keeping your CSS modular... writing CSS that applies only to one "component" of a page (e.g. a box in the sidebar or a header logo or a navigation menu or whatever). LESS and SASS have more to do with the fine-grained details of CSS syntax... primarily reducing repetition (via nesting, mixins, variables, etc). I personally wouldn't worry about any one particular technology (other than CSS itself), but I have found over the years that the most immensely helpful technique when working with CSS is keeping things as modular as possible. Basically, ignore the "C" (Cascade) in CSS, either with compiled / scoped components (like the linked article is talking about) or through a naming convention like BEM or SMACSS.
- afarrell 9y agoIf you have no background in CSS+HTML, you probably want to actually start by learning a clear mental model for how CSS and layout actually works. Otherwise, working with CSS is going to feel like https://imgur.com/gallery/Q3cUg29 https://imgur.com/gallery/Q3cUg29. If you are actually able to predict what layout would result from a small snippet of CSS and HTML, it makes things much easier. So how do you get there from 0? 1) Read this page: https://developer.mozilla.org/en-US/docs/Learn/CSS/Introduction_to_CSS/Selectors https://developer.mozilla.org/en-US/docs/Learn/CSS/Introduct... and then play this game. https://flukeout.github.io/ https://flukeout.github.io/ 2) Open a file in a text editor with a <style> element and a <body> element to play around with. 3) Enter file:///path/to/that/file so you can view it. 4) Download a Spaced Repetition flashcard app like https://apps.ankiweb.net/ https://apps.ankiweb.net/ For more on how Spaced Repetition works, see https://www.youtube.com/watch?v=eVajQPuRmk8 https://www.youtube.com/watch?v=eVajQPuRmk8. 5) With all that open, work through http://book.mixu.net/css/ http://book.mixu.net/css/ As you are going through it, test things out yourself and take notes. Make flashcards that test your ability to remember why certain things work the way that they do. Also make flashcards for things that seem surprising. Try to keep them small and focused. 6) When you get to the flexbox section, take a break and play this game: http://flexboxfroggy.com/ http://flexboxfroggy.com/ If you are the sort of person who likes understanding things at a deeper layer of abstraction than you actually work, read https://www.html5rocks.com/en/tutorials/internals/howbrowserswork/ https://www.html5rocks.com/en/tutorials/internals/howbrowser...
- callmevlad 9y ago> "But at the end of the day, you have to know CSS anyway" If you string-replace "CSS" with "assembly", most of Bret Victor's "The Future of Programming" [1] still seems to apply. People used to argue this passionately that knowing how to write assembly by hand was critical to being a good programmer. > "Love it or loathe it, you must at least learn it." This might be true today, but it would be a shame if tooling didn't level up to a degree where CSS becomes mostly a compile target (just like assembly is today). At the end of the day, CSS provides styling tools for a massive medium, one that should be accessible much further beyond the 0.25% of the world that knows how to code. The main way we can unlock that is with better tools and better abstractions. It's wholly unrealistic to get everyone to be as good at hand-crafting CSS as the author, nor should it be the goal. CSS is getting more and more powerful and more complex, and it's unrealistic for folks to continue hand-crafting in perpetuity. Even today, with some of the world's best software engineers, I routinely see this: * Most devs don't know how to create a radial gradient from memory * Most devs don't know how to hand code shape-outside code, especially polygon * Most devs guess-and-check repeatedly as they work with Flexbox props and use cheatsheets even after years of practice (while designers are running circles around them using visual abstractions like [2]) * CSS Grid minmax formats, don't get me started... I personally love crafting CSS by hand, there's a certain satisfaction to it. But if that's the primary way that folks are styling stuff on the web 5 years from now, to me that would imply that we did a bad job of exposing this wonderful technology to orders of magnitude more people. --- [1] http://worrydream.com/dbx/ http://worrydream.com/dbx/ [2] https://www.flexboxgame.com/ https://www.flexboxgame.com/
- rich_harris 9y ago> Most devs don't know how to create a radial gradient from memory I think I largely agree with you — giving more people the ability to build and design stuff with web technologies is something I care a lot about. To me, the answer is to build better tools around CSS, rather than creating a multitude of abstractions and creating tools that target those. My belief is that CSS tooling hasn't evolved as quickly as JS tooling (and hence CSS-in-JS) because the JS community has often had a bit of a snooty attitude towards CSS and people who write it. That's something I hope we can change.
- DamonHD 9y agoI like the declarative nature of CSS. I find that keeping what I do simple and small and well documented makes the simple stuff I do easy to maintain. Yes, I can write you (another) 100kloc of Java or C++ or JS if you really want, but I did also enjoy Standard ML and Prolog over more and more imperative code with exciting race and portability issues.
- monfera 9y agoJust adding it here as well: if one likes editing CSS files in Chrome Dev Tools, then activating Workspaces will save such changes into the source file. This Dev Tools integration with the Svelte approach is so useful that it might actually tilt the choice in favor of CSS files over the more abstract, thus Chrome-uneditable CSS-in-JS (Workspaces are doable with SASS too as per https://www.amazeelabs.com/en/How-to-write-Sass-within-Chromes-DevTools-using-Workspaces-and-Auto-reload https://www.amazeelabs.com/en/How-to-write-Sass-within-Chrom...).
- inglor 9y agoWorth mentioning that CSS-in-JS _and_ CSS-in-CSS hot reload in any modern build system anyway. So using workspaces used to be super useful but it's not a big selling point any more.
- monfera 9y agoI'd agree with it were it not for the huge difference between the view refresh latencies. Within the browser, it's near-intantaneous. Hot module reloading (which is still experimental) is relatively fast, yet there's a couple of seconds of a trip; also depends on what and how changes. Full page reload can take even longer, there's compilation time, bundling and the unavoidable cost of reloading stuff in the browser. Sure a couple of seconds doesn't sound bad but it's still a couple of seconds longer than what it should be (immediate) and it breaks my (work)flow.
- rich_harris 9y agoAnd you lose state, unless you've carefully designed your app around that problem by using something like Redux. Which is a fine thing to do, but not everyone wants to.
- porsager 9y agoThe chrome dev tools API has a neat function to inject new source code by only replacing all functions from the new code, thereby keeping any state. I've used this when building wright (https://github.com/porsager/wright https://github.com/porsager/wright) to allow for hot reloading of anything (no need for redux). CSS reload is also instantaneous with wright, so might even make sense for you to use with the setup you described - No need for copy pasting ;) You can see it in action here https://porsager.com/wright/example.mov https://porsager.com/wright/example.mov - The start is editing js code (a mithril app) that is going through rollup, but there's also editing of raw css files at the end.
- sayurichick 9y agoi work in react, so i just create a <componentname>.css file in the same directory and `import componentname.css` in my component. I get the advantage of using either Sass or less or postcss with webpack and I get all the features as expected from this workflow. The only thing I don't have is that unused class feature with my workflow, but I can probably find a postcss plugin which handles that. I don't see any advantage of this library for me?
- rich_harris 9y agoThe CSS developer experience is just one small aspect of the framework. The advantages are spelled out more fully in [this blog post](https://svelte.technology/blog/frameworks-without-the-framework https://svelte.technology/blog/frameworks-without-the-framew...) — Svelte compiles your components to lean, very fast JavaScript. It handily outperforms React, and your app will almost certainly be smaller and start quicker. You're unlikely to find a postcss plugin that can eliminate dead code. Unless it can analyse your CSS in the context of your markup, it has no way of knowing what's safe to remove. For that, you need statically analyzable single file components.
- madeofpalk 9y agoNo reason why Webpack/`import css` couldn't eliminate the CSS from this // styles.css .root { background: grey; } .button { border: 1px solid blue; } .error { color: red } .alert { background: red } // Component.css import styles from './styles.css' return ( <div className={styles.root}> <button className={styles.button}>Submit</button> {false && <div className={styles.error}>Error!</div>} </div> ) Both the .error and .alert are candidates for being removed. Of course, I'm not aware of any solution for nothing this currently, but all the bits and pieces are there for it to be feasible.
- muthdra 9y agoI'm just a dumb bug, but it's possible that this dude is betting on keeping it simple by avoiding alien syntax and additional transpilation steps. In browsers, this usually makes errors more relatable to the canon, readable source code your team uses.
- krmboya 9y agoPerhaps if the web had started off as dynamic instead of static we'd have several styling minilanguages to choose from, that worked the same on all browsers, rather than the mess introduced by letting the browser wars dictate web standards.
- dfabulich 9y agoThere is no real alternative to letting the browser vendors dictate web standards.
- Kiro 9y agoHow is Svelte solving these problems in Vue Components? > 2. A child component's root node will be affected by both the parent's scoped CSS and the child's scoped CSS. > 5. Be careful with descendant selectors in recursive components! For a CSS rule with the selector .a .b, if the element that matches .a contains a recursive child component, then all .b in that child component will be matched by the rule. https://github.com/vuejs/vue-loader/blob/master/docs/en/features/scoped-css.md https://github.com/vuejs/vue-loader/blob/master/docs/en/feat... If it's the same in Svelte I don't see how scoped CSS solves anything. I still need to be careful not to let the CSS bleed into the child components.
- rich_harris 9y agoIt's not the same. Styles declared in a Svelte <style> block only pertain to that component, unless you opt-in to the cascade with a little bit of extra syntax borrowed from CSS modules: `:global(.foo) {...}`. You can also compile Svelte components to custom elements, which use shadow DOM to enforce complete style isolation (though this is a new and experimental option).
- spankalee 9y agoShadow DOM is the real answer here.
- madeofpalk 9y ago> I still need to be careful not to let the CSS bleed into the child components. In practice, this means not to use selectors like .a * which is pretty easy to avoid (and you probably should be anyway)
- seanwilson 9y ago> The biggest problem with CSS Everything in CSS is global. Because of that, styles intended for one bit of markup often end up affecting another. Because of that, developers often resort to wild namespacing conventions (not 'rules', since they're very difficult to enforce) that mostly just increase your risk of RSI. Hmm, I don't find namespace issues a problem to be honest. Generally I use a framework (e.g. Bootstrap) where I don't reuse any of its names, I have some global styling (e.g. buttons, forms, typography), each major screen/component gets it's own file with its own class identifier (e.g. page-home for the homepage) then in SASS/SCSS I make sure everything everything in each file is nested under the screen/component identifier (e.g. so everything to do with the homepage is nested under .page-home). It's going to be very obvious if you get a naming conflict and they're not hard to resolve. Is there anything wrong with the above approach? You'd need something different if you were designing your own framework or general components across a huge website but for SPA and typical websites I don't see the need to make it more complex than this.
- madeofpalk 9y agoIf you're just using Bootstrap and its classes, then you're probably not in the 'target market' for something like this. I think you've actually agreed that Scoped CSS is really useful, but you just implement it manually by using a naming convention. What if you didn't have to worry about that and the language just worked like that normally?
- seanwilson 9y ago> I think you've actually agreed that Scoped CSS is really useful, but you just implement it manually by using a naming convention. What if you didn't have to worry about that and the language just worked like that normally? I agree scoping is universally useful in coding, I just can't empathise that the lack of proper namespacing in CSS is a huge headache when it takes little effort to emulate it by nesting classes. Unless there's more to it? Language support is nice though.
- madeofpalk 9y ago
- spankalee 9y agoNote that the benefits of scoped CSS are completely independent from single-file components. The key idea is that with CSS and DOM scoping you write simpler, easier to understand, stylesheets and templates, which massively improves maintainability. In Polymer elements, because of Shadow DOM, selectors are considerably simpler and shorter, often just using a tag name or id. Templates for a single component often fit in one screen, so you can more easily see if a selector is used. As we get into more declarative template formats and better static analysis, we'll be able to see if selectors are used even for dynamic classes and attributes.
- firefoxd 9y agoOne thing i learned with css is that as a programmer you have to take it seriously. We generally don't consider it a programming language so we work on it the least, more often then not we don't even include it in our completion estimate. To do CSS at scale requires organization and planning from the very beginning. If you start with bootstrap, you can't just deviate down the line. If you follow the BEM convention you not only have to stick to it, you have to enforce it so everyone in the team follows it. Currently I work on 2 MVC project, and just like every component has a view, each also has it's own css file. We don't have to wait for compilation since .net has a realtime css update, and php doesn't need to compile in the first place. But for each project, i have to train new members to follow the convention.
- seanwilson 9y ago> One thing i learned with css is that as a programmer you have to take it seriously. We generally don't consider it a programming language so we work on it the least Agree with this. I've seen frontend work collapsing under its own weight because the CSS was kept in one huge file, you couldn't tell what was dependent on what, JavaScript was being used to alter the DOM based on classes and window resizes, there were around 20 different media query size widths, nothing was shared as variables...changing anything was terrifying and took forever. You need to keep CSS modular, stick to naming conventions, reduce duplication and keep code concise; exactly like you do with regular programming languages. You can get far with CSS without any programming knowledge but at a certain scale you need to understand good coding fundamentals.
- crimsonalucard 9y agoI think browsers need a pixel level api that someone can compile a layout engine down to. Sort of like webassembly for layout instead of logic.
- pier25 9y agoYou mean like WebGL or canvas?
- crimsonalucard 9y agoNo, outside of canvas. Make the pixel api the parent and html/css the compile target.
- pier25 9y agoCan you elaborate?
- crimsonalucard 9y agoThe model of html/css is not designed for the ground up for modern layout. It was a tool designed for a separate purpose with features hacked on over the years to make it work. Nowadays a website is no longer just a document. It's an application. Why have html/css the one crude way to make a web application? In the backend we have a constellation of apis, frameworks and languages to build an app, but in the front end it's HTML/CSS/JS. The role JS played is generalized by WebAssembly, it's time to do the same for HTML/CSS.
- pier25 9y agoYes, but what would be the advantage of having low level HTML/CSS? WA gives us performance. Before WA you could already write with many languages and output JS.
- crimsonalucard 9y ago
- balloob 9y ago> How can we reuse constants that are defined in a single place? The answer for this is already in your browser: CSS custom properties http://caniuse.com/#feat=css-variables http://caniuse.com/#feat=css-variables On top of that the CSS working group is working on ::part and ::theme pseudoselectors to help theming across components. Brief intro in this Polymer Summit 2017 talk: https://youtu.be/rvpJ5O0W_6A?list=PLNYkxOF6rcIDP0PqVaJxqNWwIgvoEPzJi&t=1180 https://youtu.be/rvpJ5O0W_6A?list=PLNYkxOF6rcIDP0PqVaJxqNWwI... (skip back to 16:17 to hear why the CSS mixins proposal didn't work out)
- tannhaeuser 9y agoIf scoping CSS is such a big deal, I've got to ask if its not easier to just go with inline-CSS instead. It's a matter of whether specifying styling rules separately from content markup is a good fit to your app or doc, or if you're rather working around an undesired far-distance effect of CSS. If you need complete style isolation from the rest of your site, then you're really writing HTML markup to express an UI, so why not express it in a single artifact or dynamically generated HTML along with properties in plain old HTML style attributes?
- nateroling 9y agoInline CSS is underrated. Sometimes you just need one big red button, not a .big-red-button class.
- y4mi 9y agocss doesnt constrain you to classes. there are other selectors as well.
- jbreckmckye 9y agoYou seem to be calling out BEM as a "crazy namespacing convention" - but as awkward as those underscores are to type, they _do_ seem to do the job. I'm just a bit lairy of adding yet another proprietary tool to my buildchain to try and bend the web platform to my will.
- NathanCH 9y agoAnyone who dismisses BEM because of the syntax is missing the point of BEM entirely.
- monfera 9y agoI think there are other reasons for dismissing BEM, it's quite an opinionated and shallow structuring, good for some stuff and not for others. Very HTML tag oriented, for which we have, well, HTML tags already. Its claims are simply not true (eg. "Reduces style conflicts by keeping CSS specificity to a minimum level."). Even in syntax, it saves on silly things (".btn"?) and wastes much more on, in effect, introducing Hungarian notation to CSS. I could go on but no time rn
- NathanCH 9y agoPlease do go on. Can you explain what you're talking about re: HTML tags? Maybe brush up here http://getbem.com/naming/ http://getbem.com/naming/
- rich_harris 9y agoI don't work at the Guardian any more, I'm at the New York Times, where we are starting to use Svelte for some stuff (see e.g. https://www.nytimes.com/interactive/2017/08/09/upshot/game-of-thrones-chart.html https://www.nytimes.com/interactive/2017/08/09/upshot/game-o...). Though I haven't spent a lot of time evangelizing it to my coworkers here to be honest — if people are happy with their current tools then I've got no interest in shoving Svelte in front of them. > I'm just a bit lairy of adding yet another proprietary tool to my buildchain to try and bend the web platform to my will. By using Svelte I've found that I no longer need to bother with any CSS pre/postprocessors or minifiers (I was mainly using them for scoping, which is no longer necessary), and I don't need to faff around transpiling JSX. So you might find you add one build tool but get rid of two others!
- reificator 9y ago> It warns on and removes any unused rules, then it minifies the result and lets you write it out to a .css file. So... is `el.classList.add('error')` going to do nothing if the source contains an otherwise unused error class? Is there some comment flag that prevents this behavior? Do you need to shut off the analyzer completely, or add extra hidden markup to also consume your dynamic classes? Does it handle media queries? Or new/upcoming CSS features like the replacement for the attempted mixin standard? (:theme and... something or other...) I'm all for finding dead rules, but if it automatically eliminates them I worry it'll be easy to accidentally trick.
- rich_harris 9y agoFor the static analyzer to work, you'd need to add that error class to the template (`<div class='{{error ? "error" : ""}}'>` or something). But that's okay — it's the whole point of state-drive UI, and happily it's much easier than manually manipulating the DOM in a way that keeps track of state. It's a feature, not a bug ;) Yep, it handles media queries. It should handle ::theme just fine (since it doesn't know what it is, it'll just ignore it), but since it's not implemented anywhere I haven't tested that yet!
- reificator 9y agoAh, that's a good point. Despite using Polymer, React, etc... for side projects, my primary browser target remains IE8 in quirks mode, so I forgot modern UI patterns for a moment. Sounds good, thanks for clarifying.
- swiftting 9y agoThere's no better feeling when you can write some clean CSS in a wordpress template to make it do what you want!
- graphememes 9y agoScoped styles don't work properly for child nodes.
- rich_harris 9y agoWhat do you mean?
- deleted 9y ago[deleted]
- prograhammer 9y agoI'm completely dumbfounded how everyone has missed that the simple problem of scoping in CSS is naming. I work with Vue and Stylus. You already have to give your JS components a name. Your styles can use that name. I don't need my styles inside the .vue files. I just keep them in a separate file: /styles/components/foo.styl. At the top of your Stylus file you give the name of the component (.foo) once. Even further, you can prefix it (.my-foo). That's the namespace. Then all your styles can be written under that with a methodology like BEM. Now you get scoping AND you can still load up your variables/settings first, via a main.styl. Otherwise, if you put styles in your .vue files then you need to remember to import variables each time. Also it becomes an issue to discern which classes in the component are from you and which are from a vendor (ie. Bulma, Boostrap). Then think about libraries. You can't work with styles that are in the vendor's .vue files (without adding more specificity). I wish that library would have provided me its separate SCSS/Stylus styles instead. Am I missing something here Rich? (btw, love your work in Rollup!)
- rich_harris 9y agoI personally prefer the co-location of styles and markup, because it means I'm context-switching a lot less. And it's essential that the compiler can analyze the styles in the context of the markup to which it applies in order to do things like dead code elimination. But support for external files and preprocessors is on our roadmap.
- arxpoetica 9y agoI have setup my own methodology for loading external files and preprocessing (ala postcss and whatnot) which works to my preference. As well, one can still namespace to match. Win-win.
- prograhammer 9y agoAlright, this discussion got me thinking. I think this is the way to go now. The bullet list: -- All separate style files (for non-vue-component styling, such as variables, functions, and CSS-only components) use BEM. All styles inside Vue components also use BEM. Consistency! -- Use Stylus in the Vue components. Vue-loader supports preprocessors. Why a preprocessor? Mainly for theming. Why Stylus? It’s just so beautiful. -- Using BEM inside vue components means I don’t have to worry about collisions (with global, or children, or vendors). -- Mental context-switching is reduced now since component styling lives inside the .vue files. -- I don’t mind using #app to override vendor component styling. -- Better scenario for Dead Code Elimination to work with when putting styles in .vue files. -- I don’t mind importing variables/functions/theming to each component until this is solved in the future. Plus, I could create a bootstrap.styl (not to be confused with Twitter Bootstrap) to import everything I need so I’m only adding a single file to each Vue component. Any changes made are made within boostrap.styl and Vue components would not need to be updated.