985 points · by aarohmankad · 7y ago · 182 comments
Things like SwiftUI and React are showing that declarative UIs can be built by tying the style to the layout and allow for much better accessibility, tooling, overall thinking of how UIs work.
So to me CSS feels a bit outdated since big companies are definitely moving away from this separation. How does HN feel about this?
Experimented a bit with CSS-in-JS, which is designed to get rid of this separation, and I found it to ultimately be harder to maintain than SCSS. This process was also what got me hooked on BEM after being initially pretty skeptical about whether it had any real value.
I now believe that BEM would meet the needs of most teams, with the exception of a few massive software houses like Facebook. And most companies don't fall into the Facebook category, even if they think they do.
I've also taken some time to reflect on older companies I've worked for, particularly some work I did at Oracle, which was for a reasonably large team spread across several continents. I think BEM would have been good enough for us there as well.
I would propose the following test: Is your front end in a monorepo? If so, BEM is probably good enough to solve any problems with scope and style conflicts. If your code can fit in a monorepo, I think its unlikely you will ever have a legitimate reason to duplicate a component name in multiple places.
Take it or leave it, just my experience, I'm sure other people would advocate different things. But it's by no means a settled debate, different people/orgs have come to different conclusions. It's just that one side writes a lot more blog posts.
* naming of classes
* creating components whose sole purpose is styling
* eliminating unused stylesheets
It’s not like we became any less strict about specificity or used inline styles any more or less than we did with BEM. I find the differences to be purely logistical. Styled Components simply automates a lot of the grunt work and allows us to focus on more important things.
I've found it much easier to not have left over or unused cruft with component styling JSS/StyledComponents etc.
We import shared styles for typography, color, and some layout basics, but each component gets its own CSS file.
Used to be a hardcore Sass lover, and CSS modules took a small amount of getting used to, but worth it in the long run.
The only part I dislike about CSS Modules is having to use camelCased class names, or string references (styles['class-name']), which always feel awkward. I prefer kebab-case for CSS because it's a lot more flexible (more word separators: "-", "--", "_", "__", etc.), but I'm sure I'll adapt.
1. naming rules almost always lead to verbose inelegant names that humans would not really use at some point. (I said almost to ward off a war)
2. The part of CSS that I am generally better at than most developers is specifically in understanding the cascade. BEM, in order to help the people who are not good at the part that I am good at, pretty much makes it impossible to use what I am good at. I feel like I'm being Harrison Bergeroned every time I use BEM. But also the names I have to give things rankle.
Then I tried in a practical, everyday development setting and found out I was just wrong :)
In the hundreds of projects I've used it on it has only make maintenance easier and intentions much more clear. Having a flatter css structure is much easier to work with too. The classes do look ugly though, and was a point of contention when I first looked at it. It was the same when I first saw JSX in React too. I hope a native scoped css solution becomes commonplace so we can avoid having to use a naming convention to achieve the same thing.
You're welcome to disagree of course, I held a somewhat similar view to you until I tried BEM in a production setting.
And of course, different products call for differing methodologies. I haven't yet switched my personal blog over to BEM, for example.
If a human isn't going to read the CSS and the computer handles it without performance problem, I say no.
Those are of course two quite important ifs!
Definitely worse than my usual approach of writing some LessCSS and trying to be quite specific.
CSS is decent enough for overall theming, but quite bad for actually laying things out.
I think CSS's cascading and inheritance are bad design choices for most of the things that people actually use CSS for.
The alternatives need to do better. Or, I need to find out which alternatives are already better.
To start with, the only good way to do CSS in JS is to use a library that compiles your styles at runtime and inserts them into the document under a style tag. If you're not doing that, you lose the ability to use pseudo-elements and pseudo-selectors like hover. Probably 95% of the time, using CSS will be easier than setting up an event system to monitor all of this stuff yourself.
React's default tutorials will almost always tell you to pass styles manually into components, and ironically this reintroduces a lot of the problems with cascade that we're trying to avoid, because it's very easy to apply multiple styles in the wrong order or forget that some style is getting overridden. It can also make it very difficult to figure out where styles are coming from in code. So definitely don't follow that advice -- at the very least use a runtime compiler that doesn't spit out any inline styles.
There are plenty of libraries that will handle runtime compilation, but many of them come with performance costs. Enterprise software has a reputation of being slow, for good reason -- it usually is slow, because it's framework heavy and handles weird edge cases, and it's developed by multiple people over multiple years. I worry about performance more at work than I do on personal projects.
Aside from performance, I was finding that it was irritating to track class prefixes for dynamically compiled styles. One advantage of BEM is that it's really, really easy to debug. You always know exactly where a style is coming from, you always know where in code to find it, and you always know what class to use in the (hopefully rare) case that you need to hack together some selectors someplace in your code.
On the ecosystem side of things, there are a number of tiny annoyances if you're using React -- Webpack can handle live style updates if you're compiling a stylesheet. If you're compiling your CSS in Javascript though, Webpack can only reload the entire page. I found this made iteration and design a lot slower. Maybe there's some setting someplace to fix that behavior, but I couldn't find it and I didn't want to waste the time trying to build my own solution.
Finally, on a personal level, I was finding that putting my CSS in the same file as my component logic was making it very hard to organize everything and quickly grep sections of the code. This is probably personal preference for a lot of people, but I've found that disorganization is one of the biggest risks for large applications. Everyone tells me that you can still keep your JS-styles in a single file, and people will be good, and they won't split it across multiple sections of code or files -- I don't think that reflects the reality of most software development. I want the people I'm working with (and myself) to fall into a "pit of success" where organization is concerned.
Putting all of that together, the biggest thing was that I was messing around with all of this technology, finding that it was not as tightly integrated or as seamless as everyone said it was, was spending a lot of time debugging stuff, and I asked myself -- why?
IMO the biggest problems to solve with external CSS is style cascade, it's conflicting class names, it's selectors that apply across multiple components. BEM solves all of these problems for most codebases I've encountered, and doesn't require any extra libraries or frameworks. I hate debugging third-party code, and I can count on one hand the number of third-party libraries I've used on the web that I've never needed to debug. So a solution that solves all of the problems we face at work without introducing edge-case behaviors or extra dependencies is nearly always the right choice to make.
There is a rare case where you want to make your own custom CSS behavior that can only be handled through Javascript, but this is usually a bad idea because of performance concerns, and it's usually better to handle that as a separate, global polyfill anyway.
It still remains a fantastic way to style a document. The cascading nature of CSS works great in that context. But styling UI components is something quite different.
UIs are presumably more consistent/less varying than documents, so special cases and cascade overlaps should be less of a thing?
You need a different styling inside a specific visual component? You need to fight specificity and override a parent ir a grandparent or a global style.
In most UI systems this is not a concern.
This separation does get in the way in certain modern web apps, where content is basically scrambled garbage without proper presentation.
CSS that affects the components appearance (colours, type etc should be with the document).
Of course, communication across teams will affect how successful this is. I’ve seen it go both ways.
PS - read ‘should’ as ‘makes my life easier’
This includes additional/adjusted fonts, colors, etc.
Actually, I think CSS sucks at most things. Now CSS grid and flexbox are sold as solutions for long-standing layout deficiencies - and they undoubtly are a progress over grid frameworks using floats. But the real question is what is gained by pretending we're editing a hierarchical document (using HTML envisioned for casual academic publishing like it's 1999) when we layer a layout engine on top of it complicated enough to abstract that 1999s HTML into a grid and constraint-based layout? Why not just write markup representing that conceptual layout in the first place? We now have an enormous syntax proliferation of a markup language with an additional, redundant, and idiosyncratic item-value syntax (CSS) but still can't specify layout constraints in their more natural form as systems of inequalities.
It never was, layout is part of stylesheets. Do you mean separating content from presentation?
Almost all HTML is generated these days, and the information that's useful for styling is available in the same place as the information that's defining HTML. So generate the styling inline in the same place. If your address display component use a 14 point font, put that inline in the code that generates HTML for an address display component. If you need to change it for all addresses, you can change it in that code. If you need one address display to be special, use a subclass or whatever mechanism you would normally use for one special address display. Compress your HTML in transit if you're worried about the inline styles wasting bandwidth.
Recently I've been using webcomponents a lot for this, mainly because it makes the code accessible for those who don't know javascript and don't have an environment set up - just load the script at the top of the page and you can use <my-component> wherever you want in the html with the styling/functionality already taken care of. With those in place anyone can update a css file to lay things out appropriately.
The biggest problem with CSS is that it is essentially global state, and you can get tricky action-at-a-distance effects that you never considered if you happen to wrrite some ids that something else is expecting to own and their selectors are poorly written. Or you can monkey-patch over it and break other things.
Tightly scoping things can make CSS workable, but requires discipline. And things that require discipline to do right don't scale well.
As with anything in technology, it depends on the task and what you're trying to achieve.
The size of the site is a major factor, as is how optimized the owner wants it to be.
Saying that "big companies are definitely moving away" from anything is always going to be a gross and inaccurate generalization.
The pain will continue until people understand.
Many such cases. :)
Point is, HTML is a document format, not a UI toolkit. That's how it was designed and that's how it continues to evolve.
This is probably not a ideal situation, but trying to change it now probably won't do any good.
That's what we call JavaScript and CSS. You can do that without React and my company has been doing that for 15 years quite successfully--with separation of the elements and styling.
How do you think SwiftUI and React do such things? With JavaScript and CSS!
(Sorry if I have factual errors about SwiftUI cause I really don't know anything about it.)
( margin-top: you start dealing with parents inheriting the margin - which is an old quirk of CSS - it's a side-effect you need to control, so the usage of margin-top should always be avoided and margin-bottom should be the preferred solution owl selector: performance implications - it's fairly bad from a performance POV to use it. Also, we live in a world where we have control over how the layout is generated, we should avoid using generic selectors Source: I've been doing frontend and focused on CSS for over 10 years )
Not really if you consider sibling layouts, e.g.: https://matthewjamestaylor.com/css-margin-top-vs-bottom
> owl selector: performance implications - it's fairly bad from a performance POV to use it.
Arguing about "CSS performance" is futile when the real cause of bloatedness is mostly JavaScript these days (also: http://alistapart.com/article/axiomatic-css-and-lobotomized-...).
The owl-selector can actually be quite elegant, but becomes a burden if you have lots of side-by-side blocks (which would always need to set their margin-top to 0).
Was browsing through the docs for some Vue+CSS library or another recently, and the author had done quite a lot of research into this, was interesting.
They were heavily using the square bracket html-attribute selector notation, although I'm not sure if it performs better now, or if modern processors are just that much faster.
I would prefer that browser compatability is mentioned, for my own purposes that would be IE11.
Perhaps set a baseline of what browsers are considered in the intro and then highlight deviance as it occurs.
Yes, it is float based but my code is at the correct level of abstraction.
Initially they're frustrating, but after awhile you recognise the ease and predictability of styling reusable components.
It never scaled terribly well in its original state, and with every iteration became more bloated, so we came up with methods of controlling the sprawl; but imo glut of Modern CSS Implementations and their many and varied permutations not only feel like they are not only fighting against the original concepts, but also against each other.
Which isn't to say they're bad or anything, but simply that CSS is old, everything else has changed dramatically, its probably time we went back to the drawing board.
A quick google didn't reveal any browser support for it though. Anyone got a resource for that? I can see that the adjacent selector is supported on 98% of global browsers, but I would not be surprised if there were some issues combining it with * +
I'd be happy to contribute if it was open to suggestions.
It is important for the field to be welcoming and open to curious individuals who want to learn, but there is also a very real need to have literature to communicate ideas that industry professionals encounter, and that necessarily implies some level of baseline knowledge. In other words, there are already plenty of resources to begin learning CSS, and not every article has to assume absolutely no proficiency in it. Every discipline of course has plenty of specialized writing. If you pick up a Quantum Mechanics paper, for instance, you'll find that it doesn't spend much time building up mathematical fundamentals like tensor algebra or topology even though it may well be required knowledge for someone to understand the paper.
Though I'd class myself as a "full stack developer" css for a long time was the 2nd class citizen, with most of my time spent on learning to use front end frameworks in their idiomatic way, the "it depends" peculiarities of SQL and RDBMSs and making inroads on the vast tomb that represents architectuliary sound back ends.
So an article focussed on improving my "it's only css but it works" knowledge is one of the best things I've seen on HN in quite some time :)
A good full stack developer should
have double the salary of a frontend/backend
developer
There are (at least) two major reasons why this is not the case.1. While theoretically possible, it's uncommon (and given the rate of change and increasing complexity of both front end and back end stacks, unrealistic) for a "full stack developer" to have expert-level production knowledge in both domains.
2. Even if #1 was true for a given developer, they wouldn't have double the productivity (and/or billable hours per week) as somebody who was more of a front-end or back-end specialist.
It's similar to the reasons why, in the medial world, general practicioners (aka "family doctors") do not earn money that is the... sum of all other medical professions earnings. They are generalists . Their role is to solve many problems, but also to refer many problems to the appropriate specialist.
Even at the backend you have the application backend (c# or whatever) and then sql/rdbms. If you are that good perhaps you deserve thrice the pay by this logic ;).
Jokes aside, at the last good company I worked for where I knew other people's pay, I was compensated for the entirety of my skills compared to the good front end dev. We earned the same, and I was quite happy with that.
Jack of all trades...
https://flexboxfroggy.com/ https://codepip.com/games/grid-garden/
I wish all learning was this fun.
CSS level 1 is pretty short but will still teach you a big chunk of the fundamentals of current CSS even though it is more than 20 years old. After that you can focus on the changes and additions in later versions - those newer specifications are a lot more technical and precise and cover a lot more features, so they are also longer and less fun to read from cover to cover.
is all anyone needs except the standard itself.
For this reason I will be sticking with CSS Grid. CSS Grid is supported in all HTML5 browsers, so that means everything except the depreciated Internet Explorer.
To get my CSS Grid versions to work I will also be using CSS Variables defined in media queries to make things responsive. I don't need to have lots of fixed breakpoints as I use fonts that scale in such a way that lines don't get too long to read on really big screens.
For the CSS variables I have fallbacks which are the desktop defaults. So although 'mobile first' I can get a deluxe mobile experience but code for desktop in the first instance.
With pseudo classes I can add icons, usually Unicode symbols or SVG, SVG defined in CSS variables.
Since I can do this with CSS Grid and only have Internet Explorer be 'of concern', I can write HTML5 with no superfluous markup. That means no div, span or even class attributes. I have got out of the mindset of using container wrappers for content and just putting neat content where it needs to go using CSS Grid.
You could look at my HTML and think I had just swapped the div for article, aside and section. Or for figure. Or for main, header and footer. But that is not the case, I find that if I am using the right elements and pay attention to the structure of my content it just naturally styles itself with CSS Grid, no additional markup needed.
Also not needed are clever things with calc. If I find myself doing that then it is a sign that I have got it wrong and that there is a simpler solution I have overlooked. I also rarely use pixels. It is ems or viewer units all the way, again no need to think of what a pixel actually is.
I find that writing HTML and styling it without the hacks makes my code pretty alien compared to how the rest of the world is doing it. Anyone can make stuff complicated for reasons of backward compatibility, keeping it concise and simple is a different craft.
For the above reasons I am disappointed by these layout modules, a lot of work has gone into it but at times we need to question what we take for granted. Everything is a div. I look at the examples and see that if, e.g., the image is put in a figure and given a figcaption then the structure is there for it to effortlessly be given layout with CSS Grid, no container elements needed.
At some stage we need to stop looking at content as placeholder examples and stop using generic containers.
Why is that? Does Grid treat 'article'and 'section' differently than it treats plain 'div'?
I thought that the purpose of 'article' etc. was purely semantic, saying something about the meaning and purpose of content inside them, not how they should be laid out on the page.
Typically with a 'section' the first line inside it for me is a heading. So on the outline there are no 'unnamed sections'. Save with 'nav' and other content blocks, I usually find that there does need to be a heading in there anyway.
So Grid does not care what the elements are, however, that form fieldset won't work in CSS Grid and there may be a couple of other edge cases. Now here is the important thing to know - have too many nested divs and it makes CSS Grid very difficult, almost pointless.
So, imagine a form. You can have just label followed by input, label followed by input with some submit button at the end. This can be put into CSS grid and styled beautifully with no effort. It goes responsive effortlessly as well. There is nothing to it.
But then, in real life you are working with some legacy code where there are divs around each form element and divs grouping the labels and the inputs and an outer wrapper with spans around the required field asterisks, everything with class attributes on it.
It is hard to imagine if you are used to that type of markup that you don't need any of it!
But that is the case. You can write ultra lean HTML.
Then when it comes to actual content, e.g. a blog article, you realise that the WYSIWYG paradigm is doing us no favours. It has no structure even if it looks okay.
So I use the article and section elements to just get my writing neatly organised, with headings at the top of each. This is more about just writing content neatly than presentation.
The div makes sense if you are copying stuff from old tutorials, but it never makes sense with content, but it sneaks in there. It is so baked in with things like the Wordpress Gutenberg blocks thing where some people have staked the whole company on new ways of writing out of spec bad HTML. If you check the manual you will see it is the element of last resort and just isn't needed with CSS Grid layout.
Before CSS Grid layout you did need the div to make wrappers for centering stuff. But now you don't. But people have got so used to using it that it has got stuck in the mindset, a groupthink that will look silly in a decade or so.
I also style the elements, never needing classes. But with no div wrappers these are all sensible looking to me but would horrify someone doing BEM notation. Here is an example that gives you an idea...
body > footer > nav > ul {
display: grid;
grid-auto-flow: var(--footer-nav-ul-auto-flow, column);
grid-gap: .25em;
justify-items: var(--footer-nav-ul-justify-items, left);
padding: 0;
}
So that is for some responsive footer links, they go across the page on desktop and the other way on a small screen. Best practice would say that I add 'footer-links' as a class to the footer links. Best practice says the 'body > footer > nav > ul' selector is 'too complicated' as it uses four rather than three (max) selectors. But that is how I like to read my CSS these days, with no preprocessor, no compiling, just spelt out.Now this example is not a portable component but that is the point, the document structure is relatively flat and quite predictable.
The concern the BEM and component-based CSS approaches aim to address is the composition of arbitrary chunks of DOM without implicit side effects. By having chunks of DOM explicitly opt in via classes to being styled in a given way, they never accidentally receive styles they weren't meant to, and they're fully portable to arbitrary contexts.
In something like an web application as opposed to a document-oriented website, the ability to compose components and avoid quirks of things that randomly break or look different inside other things is beneficial. Using a component in a new place shouldn't (in the application development context) require adding new selectors for it because it's not "where" your selectors expected it to be.
Just a question, is article part of a section, or section part of an article ?
One thing is that when you are no longer using presentational markup then you only really have content, so it is markup with context. So I think it is a finished project I need to be able to share rather than an example.
Best get to it!
> At the time of conceiving the axiom, you make not have pictured this specific visual effect.
I'm pretty sure it should be "may" instead of "make".
>The Cluster layout is available in the full version of Every Layout, which is still in production. All of the currently available layouts are marked "read now" in the index page.
where is production? I can't find it
Also, if I remember correctly, the default browser in Windows 7 is IE9. It makes sense to support default browser in the most popular desktop OS.
Some of older browsers, released in 2012-2014 support flexbox only with vendor prefixes, but the article doesn't has rules with prefix. As frontend devs tend to copy the code without much thinking, we cannot expect that they will add the prefixes or fallback code themselves. So it will be author's responsibility for web sites being less accessible in different browsers.
> Some of older browsers, released in 2012-2014 support flexbox only with vendor prefixes
Again, these browsers represent a tiny fraction of the total market. Firefox and Chrome auto-update by default, so there is no reason that someone should be on a version from 2012.
These days it simply doesn't make sense to have a fallback for flexbox unless you're specifically targeting older versions of IE. (And even then, I've had some luck getting flexbox layouts to work on IE 10, even though it's more effort.)
I wouldn't be scared of using flexbox even if you need to support IE11. I'm not sure where caniuse's dire warnings come from. (I have run into different flexbox behavior between FF/Chrome about as often I have run into flexbox problems with IE11; I generally couldn't tell you which of FF or Chrome is correct/incorrect in those cases).
I've in the past done flexbox without too much trouble even on IE10, but I am not myself concerned with IE10 anymore.
https://inclusive-components.design/
IE11 is meant for supporting legacy sites and Microsoft doesn’t recommend consumers to use it. It make sense to work on Grid and Flexbox for new sites.
Rem units can cause issues in long term. For example, imagine if a sidebar widget is coded using rems. When later the main font size is changed, margins within widget will change its size, although the font size in it is fixed and didn't change. There are cases when rem is useful and there are cases when it is not, but the author doesn't give a choice and doesn't explain it. He just uses his authority to push his personal preferences to frontend developers who tend to copy the code from tutorials without much thinking.
I recommend using pixels for projects that are going to be maintained and developed in the long term.
The rem unit is remarkably well supported, going back to IE9, Android 2 and iOS 4.
It has a specific meaning: it's relative to the root element, which usually means it's relative to the font size the user set as the default font size for the browser — 16px by default in most devices. It's not just a stuffy alias for the px unit, used by sneaky developers to make maintenance harder.
It has a semantic purpose, which makes it useful for maintainability: if your body text is 1rem, when a heading should be double the size of body text, writing it as 2rem makes the sizing relationship between these two values immediately recognizable.
What are cross browser concerns here? Why should he even mention the possibility that someone might "fix" an elements font-size? Sure, the author doesn't explain all of CSS and all of UX/UI in an article focussed on a single issue. That's not a mistake.
Your px recommendation is... strange. The article is one of those "newer" CSS articles that care a lot about responsiveness. You seem not to care. Fine, but I guess you're in the minority there.
Your insult against front-end developers (in both your comments!) is simply childish, and frankly, it seems you just have an axe to grind with the author(s).
and
> I recommend using pixels for projects that are going to be maintained and developed in the long term.
Directly after lambasting the author for failing to elaborate, perhaps you could go into more depth yourself?
The same is about CSS variables. An example with one variable might look nice. But what if your code has hundreds of variables? It would take more time to understand how they are related and how do I change the size of this button without breaking something on another page.
But now you have to keep all those relevant "main font sizes" in your head and do constant divisions. rem units give you the ratio directly.
Also, hardcoding things instead of using variables makes things harder to maintain. If someone didn’t use variables randomly, it’s easy to update the CSS to match. Ideally, you have one css (less, etc) file that defines that variables and their relationships, just like a .h file in C, so you can quickly grasp what each variable does.
Non-sequitur. It could also become smaller and simpler.
At that point the root font size exists only as a scaling factor, decoupled from the base font size of content within the page, but allowing the user to control that scaling factor via their browser's global default font size preference. In fact, you could think of the rem as root scaling factor unit rather than root font size unit. (The use of the font size property to set the scaling factor is a quirk of the spec.)
This solves the concern you noted on maintainability, while allowing a user to globally opt into larger or smaller text and correspondingly scaled layout across the web, arguably a win for enabling an element of accessibility by default on any website.
Also, I think that changing font size in browser settings doesn't work on most sites, so people don't use it. For example, I use normal scaling (using Ctrl + +) on this site and it works good enough, and what's most important, it works everywhere. So there is no need to support changing root font size.
It's fair to point out that the browser feature is not widely used, but when it is used, it's likely by users who benefit most from the small amount of effort it takes to support it. (It's really a few lines of CSS, plus simply using rems as your websites unit whenever you'd otherwise use px. It's even easier in terms of avoiding weird 16px-based rem calculations if you make your rems 10px for a default 16px browser preference by applying a straightforward conversion on the root element.)