TE
TechEcho
Home24h TopNewestBestAskShowJobs
GitHubTwitter
Home

TechEcho

A tech news platform built with Next.js, providing global tech news and discussions.

GitHubTwitter

Home

HomeNewestBestAskShowJobs

Resources

HackerNews APIOriginal HackerNewsNext.js

© 2025 TechEcho. All rights reserved.

CSS in JavaScript is like replacing a broken screwdriver with your favorite hammer

175 pointsby kbal11over 7 years ago

48 comments

hacker_9over 7 years ago
The argument here is that CSS should be kept seperate because it is just the design and doesn&#x27;t affect the behaviour. But this really isn&#x27;t true. Want to create dropdown menus or tabcontrols? HTML just isnt enough, you need a whole set of styles in order to even create these controls. Additionally why am I able to do animation in CSS? Or insert new HTML elements?? This thing has grown far beyond simple colour switching and changing font sizes.<p>In fact the seperation causes so much mental overhead, that we need interactive browser dev tools just to be able to find what styles are applied to what element. So ultimately the idea of putting everything in one spot, per component, is actually pretty reasonable.
评论 #15219467 未加载
评论 #15219513 未加载
评论 #15220410 未加载
评论 #15221318 未加载
评论 #15223940 未加载
评论 #15219562 未加载
评论 #15219572 未加载
ddoolinover 7 years ago
I think Vue&#x27;s single-file component approach is a good solution here, allowing you to keep all three separate but in the same file with the additional option to keep the CSS scoped and add a preprocessor to it.<p><a href="https:&#x2F;&#x2F;vuejs.org&#x2F;v2&#x2F;guide&#x2F;single-file-components.html" rel="nofollow">https:&#x2F;&#x2F;vuejs.org&#x2F;v2&#x2F;guide&#x2F;single-file-components.html</a><p>About CSS in JS, though, it mostly just seems like a different way of getting the same thing on the page, changed only by the idea of scoping it to some component and maybe some needed flexibility when building dynamic CSS rules. I&#x27;m still not convinced any of those CSS approaches propped by the author are necessary or even necessarily that helpful. They can be confusing to developers not familiar with it and burdensome when truly not needed. I&#x27;m open to other opinions, though.
评论 #15219334 未加载
评论 #15219656 未加载
评论 #15219597 未加载
评论 #15219697 未加载
评论 #15220190 未加载
评论 #15219683 未加载
评论 #15219332 未加载
Wintamuteover 7 years ago
I don&#x27;t think this guy gets it.<p>In real life large web apps CSS is very coupled to behaviour and DOM structure. A large part of the advances towards _adaptable_ component-based code comes only when you let go of principles like DRY.<p>Let me put it this way, if I come along to change a feature in one of the 100s or 1000s of components in a project I _only_ want to think about the JS and CSS in that component&#x27;s folder. I don&#x27;t want to think about how that component exists in a vast web of generic CSS utilities and abstracted decoupled code. Copy and pasting CSS properties is cheap. Conversely overly abstracting your presentational code is a short cut to expensive CSS spaghetti.<p>It&#x27;s about component encapsulation, which intimately includes its visual presentation. If you can&#x27;t think of your component as encapsulated single unit then you might as well not be using components. And if you&#x27;re not using components, then for the love of God don&#x27;t use CSS in JS.
评论 #15219887 未加载
评论 #15220246 未加载
santorivover 7 years ago
&gt; Keeping things &#x27;DRY&#x27; and having reusable code rather than constantly repeating yourself is generally considered a good practice in software development. It enables fixes and changes to occur in one place, rather than having to be replicated a multitude of places throughout a codebase. It baffles me then, when CSS in JS advocates argue for essentially the &quot;copy and paste&quot; methodology when it comes to styling.<p>DRY means different things in different contexts - if you are writing a utility function that is pure and has no side effects, then of course you want to write the function once. The CSS cascade, however, has a tendency to spew side effects all over your application views (e.g. one style that affects a ton of different components), which you then need to override by adding new styles. But be careful, because your new styles have side effects also! Ad infinitum....<p>For this reason, I regard the CSS cascade as an anti-pattern in most situations. I think that ideally, you want to isolate most of your view specific css to a module attached to the view - so that you are pretty confident that it doesn&#x27;t have any side effects AND it&#x27;s easy to know when you can safely delete it. That way you can avoid specificity wars and doing a paranoid but justifiable &#x27;Search in All Files&#x27; every time you want to change a style.
评论 #15219444 未加载
onion-soupover 7 years ago
Oh stop bashing on CSS in JS already. It&#x27;s not CSS in JS, it&#x27;s CSS in component files which are -- surprise surprise -- VIEW FILES. I see nothing wrong with having dimensional and visual definitions in view files, their whole point of existence is to serve as such. You are trying to solve a problem that doesn&#x27;t exist.
评论 #15219218 未加载
评论 #15219267 未加载
madeofpalkover 7 years ago
This looks like it was written by someone who hasn&#x27;t really used a &#x27;CSS in JS&#x27; approach. The complaints are actually non existent. Any CSS-in-JS approach is going to have a way to standardize styles across your application.<p>Regardless, I&#x27;m not a huge fan of these CSS-in-JS techniques anyway (although I don&#x27;t mind Styled Components if I have to use it). CSS Modules, to me, is a far better approach and it sits there in the middleground between &#x27;Pure CSS&#x27; and &#x27;CSS-in-JS&#x27;<p>&gt; OOCSS, SMACSS, BEM, ITCSS, and ECSS.<p>The beauty of CSS Modules is that it basically merges _naming conventions_ like BEM into CSS &#x27;master&#x27;. You don&#x27;t need a convention because the language just sorts it out for you.<p>Imagine arguing against variable scope in any other language with just saying &quot;hey, just manually namespace your variables!&quot;
评论 #15220125 未加载
评论 #15225497 未加载
评论 #15219823 未加载
enkayover 7 years ago
In practice, DRY in CSS ends up making code very hard to maintain. It creates ghost side effects where you change something on one page and break something on another page unknowingly.<p>With the exception of a few elements that don&#x27;t really change at all from one page another like buttons, doing a little bit of copy pasting or search and replace between files is easier.<p>Sure, you might forget to update one page or component here and there, but at least it won&#x27;t be broken. Better a component is inconsistent in style but functional than broken.<p>Using a few variables for things like color and spacing can also help minimize this problem.<p>Keeping most of my CSS components encapsulated and &quot;namespaced&quot; has worked a lot better in practice than trying to make everything reusable and coupled together in ways that you&#x27;ll forget about when you have to come back to that project a few months later.
评论 #15219601 未加载
jakelazaroffover 7 years ago
Best compromise I&#x27;ve found: CSS modules [1] (commonly implemented with Webpack) which have you write a separate CSS file but modularizes it by exporting hashed versions of the classnames for you to use in your components.<p>It&#x27;s the best of both worlds: you don&#x27;t have to give up CSS tooling like Sass or postcss, but you gain modularity (which is really the only problem CSS-in-JS solves).<p>[1] <a href="https:&#x2F;&#x2F;github.com&#x2F;css-modules&#x2F;css-modules" rel="nofollow">https:&#x2F;&#x2F;github.com&#x2F;css-modules&#x2F;css-modules</a>
评论 #15219390 未加载
Kiroover 7 years ago
&gt; OOCSS, SMACSS, BEM, ITCSS, and ECSS<p>I&#x27;ve been writing CSS since IE6 and I was a big proponent of BEM for a long time. In the end it didn&#x27;t cut it and CSS-in-JS is the first time I&#x27;ve actually felt that the CSS problem is solved. To hear &quot;you should be using BEM instead&quot; feels like someone telling me to go back to ES5.
评论 #15223841 未加载
lilactownover 7 years ago
Every time &quot;separation of concerns&quot; and HTML, CSS and JS come up, I want to scream. I don&#x27;t think I&#x27;ve ever seen so many people have such a shallow understanding of what a term means. It&#x27;s practically a trigger at this point.<p>Everyone who is confused: <i>HTML, CSS and JS are not concerns.</i> They do not represent an intelligent way of separating your application code. Every time you write the ID of an HTML tag, or a component- or feature-specific class name, you are violating &quot;separation of concerns.&quot;
评论 #15220155 未加载
dgreenspover 7 years ago
The arguments don&#x27;t pertain directly to writing CSS in JS, in my mind. Writing CSS in JS doesn&#x27;t force you to couple your styles to your components, or reuse code or not reuse code, or be consistent or inconsistent with your styles. If anything, it gives you more options.<p>The appeal of CSS in JS to me is one less language to think in -- one less syntax to worry about and format and lint and forget semicolons in. Also, modules and defining constants. Most web developers seem to use a compile-to-CSS language and a module system these days anyway, rather than vanilla CSS.
评论 #15219247 未加载
HugoDanielover 7 years ago
How many of people that argument in favor of the CSS in JS know about the Atomic CSS approach ?<p>It is currently the best of both worlds, you can control it with JS in a proper semantic way (through class setting) while keeping 0% replication and loose coupling between concepts.<p>It also is easily extensible and composes very well. The downsides are that your CSS file is going to be a bit bigger than usual (tachyons.io with all modules goes about 84KB uncompressed, 17KB gziped). But that can be quite irrelevant in big JS oriented projects where most of the size is occupied by big libs.
评论 #15219133 未加载
评论 #15219126 未加载
评论 #15222052 未加载
评论 #15219762 未加载
encodererover 7 years ago
Most apps should have two things:<p>1) A style guide or component library that is used by both design and engineering for any commonly-used component. In some projects this could just be vanilla Bootstrap.<p>2) An inline style strategy -- there are now several good options to choose from (Styled components, glamorous, etc). A cool idea here that an engineer on my team implemented recently is using a webpack loader to convert our SASS variables into javascript variables so they can be shared with your styled components.
评论 #15219436 未加载
throwawayReplyover 7 years ago
If your solution is &quot;better practices&quot;, you don&#x27;t have a solution.<p>In the real world, people will migrate to what <i>works</i> for keeping people inline. Appealing to better practice will be mowed down by actual practice. Instead write tools which encourage better practice.
ng12over 7 years ago
&gt; It baffles me then, when CSS in JS advocates argue for essentially the &quot;copy and paste&quot; methodology when it comes to styling.<p>This is incorrect. Even if you&#x27;re using JS for styles you still follow best abstraction practices -- just instead of importing your colors and mixins from another LESS file you&#x27;re importing them from another JS file. It&#x27;s no different then designing a styling framework in pure CSS.<p>What the author is missing here is the biggest single problem with pure CSS -- reusability. Frameworks like React make it incredibly easy to reuse a widget&#x27;s logic, but what happens when I want to change the styles? JS-in-CSS allows you to do that as part of the widget&#x27;s API.
drcodeover 7 years ago
Please stop saying &quot;CSS is for appearance, Javascript is for behavior.&quot;<p>Not since the 1990s has it been feasible to write a nontrivial app in which javascript doesn&#x27;t impact the appearance of a web application.<p>The real choice is whether one does 50% of the &quot;graphical stuff&quot; in CSS and the other 50% in javascript... Or, instead, one just does 100% of the &quot;graphical stuff&quot; in javascript (independent of the merits of either approach- It may still make more sense to leverage CSS as much as possible, though I&#x27;m a skeptic of that viewpoint as well.)
joshribakoffover 7 years ago
This is like when everyone complained when angularjs put ng-click in the template instead of an .on(click) in the js. It increased productivity because I no longer had to do searches of the codebase to check if there are event listeners. I can just see that by looking at my template
tarikjnover 7 years ago
&gt; If you&#x27;re new to this space, some of the practices to check out include OOCSS, SMACSS, BEM, ITCSS, and ECSS.<p>These practices sound a bit outdated to be recommended to someone new to the space. Forget any of these and just use CSS Modules, it guarantees you not only namespacing but explicit dependency between your CSS, which most of these conventions -- which require developer effort and compliance -- can&#x27;t really offer.
评论 #15219286 未加载
swyxover 7 years ago
Are we dumbing CSS-in-JS down just to attack it? CSS-in-JS doesnt mean you have to sacrifice visual consistency or DRY principles. you can still create a central system of CSS properties and import them to be used while being explicit and scoped about the stuff that is not shared. I feel like this is being debated more than its worth. As with everything, pick the right tool for the job.
评论 #15223981 未加载
K0nservover 7 years ago
There are concerns with CSS in JS, but the arguments in this blog post are all very weak or non existant.<p>Structural&#x2F;Behavioral Vs Graphical<p>The introduction of component based tools changes how we design and build our application. No longer is the fact that you can wireframe your whole application valuable instead being able to build individual components and later compose those is valuable. This means that the graphical properties being tightly coupled to a component is actually good.<p>Loose coupling vs tight coupling<p>Component based systems can be built with loosley coupled components, but that doesn&#x27;t mean the components themselves should loosely coupled to their own implementation. This is more analgous to the native platforms too.<p>Visual Consistency<p>Claiming that CSS in JS produces visual incosistency is about as true as claiming that CSS does the same. In both cases you can be more or less inconsitent based on your chosen implementation method. In both cases you can move the lowest level design tokens[0] to a single places&#x2F;system. Arguably Javascript being a more expressive programming language is actually better at achieving consistency via the more powerful variable system.<p>Code Reuse<p>Again with a design token system in place changing the design language etc is as easy as changing a few variables.<p>Personally I think the more interesting problems with CSS in JS is the inability to extract the CSS out into css files to be shipped along the application and how that pertains to server side rendering.<p>0: <a href="https:&#x2F;&#x2F;developer.salesforce.com&#x2F;docs&#x2F;atlas.en-us.lightning.meta&#x2F;lightning&#x2F;tokens_intro.htm" rel="nofollow">https:&#x2F;&#x2F;developer.salesforce.com&#x2F;docs&#x2F;atlas.en-us.lightning....</a>
评论 #15219495 未加载
ambewasover 7 years ago
&gt; Rather than being tightly linked to structure, these are very loosely coupled - this is why one can often wireframe an entire application out before styling it!<p>Here&#x27;s one of the premises on which the article was written - and I must wholeheartedly disagree.<p>If you&#x27;re looking to write clean, maintainable CSS - you MUST consider DOM-structure of the thing you&#x27;re styling as well. Too often, quirky CSS selectors are written, only because someone failed to foresee how HTML and CSS work together to create a visual.<p>This decoupling of the HTML that&#x27;s written, and a CSS &quot;theme&quot; being written&#x2F;applied after the fact, is also where things like negative margins (ugh) and the like tend to come from.<p>Now, I&#x27;ve been working on a very large component library in React, and keeping our CSS maintainable has not been an issue. We&#x27;ve got one (S)CSS file per component, and it resides in that component folder.<p>And while the file is separate, we absolutely do not allow anyone to develop any component anymore, without having any knowledge of how to style the thing.<p>We used to do exactly that: other devs would develop component, we would try to style them afterwards. This always results in either us writing messy CSS with crazy selectors or - and more often - we simply opted to re-write the entire HTML, to suit our styling needs.<p>At this point in time though, I would love to write some CSS-in-JS here. Too often we need to use variables based on JS logic; And it ends up as an inline style right now, anyway...<p>All in all, if the writer believes HTML and CSS can be written separately, without resulting in a terrible mess, I&#x27;m having a lot of difficulty accepting that they know what they&#x27;re talking about. Sounds like they never had to work on, or maintain, a large application.
n0usover 7 years ago
<a href="https:&#x2F;&#x2F;github.com&#x2F;styled-components&#x2F;styled-components" rel="nofollow">https:&#x2F;&#x2F;github.com&#x2F;styled-components&#x2F;styled-components</a><p>strikes a really nice balance here imo. I use Radium every day and in general it has been easier to maintain and use in comparison to all css but if I could do it again I would go with styled-components.
adamnemecekover 7 years ago
&quot;As the lead for ZURB Foundation, I&#x27;ve trained hundreds of people on frontend frameworks and best practices.&quot;<p>Ok, this kinda explains everything.
评论 #15219850 未加载
adamseaover 7 years ago
Most of the author&#x27;s concerns about reusability, maintainability, and separation of concerns can be addressed by thoughtfully structuring your JavaScript application project. For example, using React&#x2F;Redux and JSS, the JSS (a CSS-in-JS technology which uses CSS modules among other things) goes in the &quot;dumb&quot; component files, not the &quot;smart&quot; (or &quot;linked&quot;) container components which pass Redux state and various functions to the &quot;dumb&quot; component. And then creating a styles.js file (or multiple files if appropriate) is a simple way to create shared JSS styles which can then be imported into various component files as needed.
ttctciyfover 7 years ago
Very readable article. My favourite line:<p>&gt; Please enable JavaScript to view the comments powered by Disqus.
err4ntover 7 years ago
I agree that often times CSS-in-JS forfeits some of the expressive power that makes CSS powerful, in the attempt to gain some muscle from JavaScript.<p>Instead of CSS-in-JS I think a better pattern for extending CSS with JavaScript is &#x27;event-driven virtual stylesheets&#x27;, which I call JS-in-CSS.<p>I&#x27;m writing a website dedicated to JS-in-CSS techniques, plugins, and theory. It&#x27;s still a heavy WIP right now, but there are ~20 plugins that can be used and code samples and links to their documentation which is good to go already: <a href="http:&#x2F;&#x2F;responsive.style&#x2F;" rel="nofollow">http:&#x2F;&#x2F;responsive.style&#x2F;</a><p>I&#x27;m trying to write down and share the results of what I&#x27;ve found trying to combine JavaScript styling with CSS for years, and the patterns and techniques that make the two useful.<p>You should be able to take full advantage of 100% of CSS&#x27;s expressive power _and_ still augment it with JavaScript logic. You can have the best of both, and this JS-in-CSS pattern works in every browser you can imagine (I recently got it working in IE7 and IE6 just for fun!(
curioussavageover 7 years ago
I think the best answer to this is three questions.<p>Is the browser being used to make dynamic &quot;apps&quot; instead of static web pages?<p>How do app frameworks&#x2F;toolkits on other platforms style their apps?<p>And finally:<p>Do you think the people who designed all of those frameworks were stupid?<p>Seems to me like the web is finally catching up with the only sane way of styling the widgets in an app. It&#x27;s done in the same language and it&#x27;s per component&#x2F; widget.
bcarroll22over 7 years ago
&gt; JavaScript used to do this, and we fixed it by encapsulating everything in modules and using tools like webpack to stitch everything together.<p>We&#x27;ve done the same with CSS, and CSS modules work extremely well. For us, they&#x27;ve even eased the need for SCSS.
colek42over 7 years ago
I have started using and evangelizing styled-components in our react projects. Hard to explain, but it just feels like it is the right way to do CSS. Having everything to do with the view for a component in one file works well for the way I work.
tomeldersover 7 years ago
CSS is for a print paradigm. But it makes very little sense in a web app paradigm. So in lieu of anything better, we encapsulate CSS with hashes, and write it in Javascript so we can have dynamic styling.<p>What we really need is a better way to style web apps.
nathan_f77over 7 years ago
I&#x27;ve been trying out CSS modules in my new project. I&#x27;ve also set up a library that generates Flow type definitions, so I get static type checking and autocomplete for my CSS classes [1]. It&#x27;s pretty awesome, and works with SASS too. I love having every React component self-contained. It makes refactoring and reusing code so much easier.<p>[1] <a href="https:&#x2F;&#x2F;hackernoon.com&#x2F;type-safe-css-modules-with-flow-dd95e761bbe5" rel="nofollow">https:&#x2F;&#x2F;hackernoon.com&#x2F;type-safe-css-modules-with-flow-dd95e...</a>
JoshMnemover 7 years ago
Elm CSS looks interesting: <a href="https:&#x2F;&#x2F;www.youtube.com&#x2F;watch?v=W4Xnas3exk0" rel="nofollow">https:&#x2F;&#x2F;www.youtube.com&#x2F;watch?v=W4Xnas3exk0</a>
DonHopkinsover 7 years ago
Why can&#x27;t people just not go out of their way to write crap CSS in the first place?<p>There seems to be this trend to show off all the possible different ways you know of addressing a single element somewhere, by pointlessly combining them together in brittle ways that depend on each other and accidental document structure, using haphazard random inconsistent naming conventions.<p>If there&#x27;s only one of them, then use a fucking id.
评论 #15223902 未加载
评论 #15219554 未加载
dmitriidover 7 years ago
&gt; The Real Answer: Better CSS Practices... &gt; If you&#x27;re new to this space, some of the practices to check out include OOCSS, SMACSS, BEM, ITCSS, and ECSS<p>This is not a real answer. It&#x27;s an attempt to fix the broken screwdriver with ducktape, bird poo, and spit.
评论 #15219858 未加载
thinbeigeover 7 years ago
&#x27;Broken screwdriver?&#x27;<p>Don&#x27;t get OP&#x27;s analogy. Does he mean CSS?<p>While CSS can sometimes be nerve-racking it&#x27;s the most modern layouting system. There was a reason that the React Native team chose CSS&#x27; Flexbox for their layouting system.
yuchiover 7 years ago
This article is a little bit flawed and a little click-bait-y also.<p>CSS-in-JS is more or less enforced-CSS-modules + some sugar + a different way to author your styles.<p>Most of the arguments there are against CSS modules, or “isolated styles”.
评论 #15223876 未加载
nikolayover 7 years ago
Very well-put! In trying to solve one problem, we create tons more. So much more added complexity! The React stack is growing out of control with the flavor of the day changing daily per se!
enturnover 7 years ago
Like religion there&#x27;s no one true way but I hope people agree that using analogies in technical discussions adds to confusion and is best avoided.
AJStacyover 7 years ago
The Shadow DOM solves all of CSS&#x27;s scoping problems.
nkkollawover 7 years ago
What&#x27;s wrong with web components? They solve the problem very elegantly, and thanks to Polymer and others we can use them today.
k__over 7 years ago
I even use CSS in JSX, while some people would consider JSX alone madness already, but it feels really nice to write it that way.
azr79over 7 years ago
Tell that to ReactJS devs, those mad men include even HTML in their JS files, how insane do you have to be.
devsmtover 7 years ago
not all CSS is equal: if you define global styles like h1{color:#000;} you want them outside components, in components you want the minimum of css needed to render correctly your date picker or whatever you are trying to accomplish and you want minimize external dependency on the global css.
hfourmover 7 years ago
I have highly been enjoying &quot;CSS&quot; in JS with React and things like Radium and AphroditeCSS
xXinVeRteDxover 7 years ago
LESS&#x2F;SASS takes care of this with nesting (ie. scoping css rules).
megamindbrianover 7 years ago
I&#x27;ve worked on many different codebases. CSS and script tags add to the mess something awful. For cleaning CSS I take an existing site open with developer console and click through every HTML element in the tree looking for alignments offsets, centering madness before flexbox, font size and color corrections are all stripped away. These settings belong in the top level body or global part of the CSS. I flatten out the HTML and CSS alike so all my elements are at most 4 levels deep.<p>This is a process that takes about 1 day per product page. It&#x27;s a horrible pain to clean up a site but the payoff is easier maintenance in the future and hopefully some acknowledgement that the page loads better. This skill can easily be trained in to developers. I hope this reminds everyone that computing is a skill that must be practiced.<p>It isn&#x27;t normal to use tables for layout these days, just like it is no longer normal to use JavaScript for centering elements vertically. This is fixed with flexbox. Please learn and use it!
评论 #15219587 未加载
megamindbrianover 7 years ago
HEY LOOK, NO ONE CARES ABOUT YOUR PROBLEMS! <a href="http:&#x2F;&#x2F;caniuse.com&#x2F;#feat=style-scoped" rel="nofollow">http:&#x2F;&#x2F;caniuse.com&#x2F;#feat=style-scoped</a>
naranianoover 7 years ago
Image macro memes in 2017 is like putting fingers down my throat.