Hacker News new | past | comments | ask | show | jobs | submit login
Relearn CSS layout (every-layout.dev)
985 points by aarohmankad 11 months ago | hide | past | web | favorite | 182 comments



To me an evident thing in UI development is that separating stylesheet from layout isn't really a thing anymore and the benefits of this separation aren't really that clear.

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?


I work as a web developer for an enterprise-level software company.

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.


BEM seems to be "Block Element Modifier"[1] if anybody wonders.

[1]: http://getbem.com/introduction/


I have the opposite experience. I’m in a React team that was doing BEM via Sass for a few years. Almost two years ago, we moved to Styled Components. The only real difference is that Styled Components automates

* 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'm with you... Also, with theme context(s) it's easy enough to re-use theme values while keeping actual component styling with the component and in isolation... you remove a component, and the styling goes with it.

I've found it much easier to not have left over or unused cruft with component styling JSS/StyledComponents etc.


I've never loved CSS-in-JS, but I do love CSS modules, which allows you to use proper CSS, while solving the biggest flaw in CSS - its global nature.

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.


Do you use Sass with CSS Modules? I've found it to be an excellent pairing. I put shared styles/variables (like colours) in top-level Sass partials that individual component styles can import if they need them.

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.


Agree with this smaller pain point in the vast peace of mind that CSS Modules bring.

I try to simplify as much as possible to a single word and repeat them a lot since there’s no collision, so you can usually expect a .container, .items, .item in most components, all top level but SASS helping with other annoyances like pseudo selectors, parents and nesting where it makes sense.


You just have to remind yourself that you aren’t writing css class names, even though it looks like css class names you’re picking js identifiers. Once I made peace with that it got a lot easier to write camelCase class names- and even switch back to kebab-case when necessary.


I have two problems with BEM -

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.


I'm not a fan of BEM, I think it neuters one of the strongest parts of CSS


I agree on the "inelegant" and "verbose", but the tradeoff is that every block became "obvious", so manteinance is much much easier than ever before.


As a front-end dev working on the web for roughly twenty years, I concur. I was late to the game with BEM and initially bristled since it goes against patterns I thought were working for me. Plus, it's not exactly terse. But, it won me over. I also agree with your comments on CSS-in-JS ... in practical terms, I feel BEM, properly executed, can handle the CSS portion of a large majority of projects.


I always stuck BEM in the same category as other more dogmatic software approaches -- nice in theory, but not particularly practical for everyday development.

Then I tried in a practical, everyday development setting and found out I was just wrong :)


Despite trying using it a few times I've never seen the appeal in BEM, it's just bringing excessive and redundant verbosity to CSS class names as well as introducing unnecessary complexity in maintenance (e.g. if you change a class's name you need to also need to apply the change to any derivative class names)


The appeal of BEM is that it offers module scoping through naming convention (because we had no other way to do it). And it stops you accidentally styling something you didn't intent to. If you have a .box with a .title inside and you write some css like .box .title { color: red; } You're telling the browser to find any title in box and make it red. But that's not what you wanted to do, you wanted to style box titles, not anything that happens to be in box with a .title, there could be sub-components with titles that you don't want to target. So instead you could write .box > .container > .left-panel > .title and maybe you've been explicit enough to get your intentions across, or you could write .box__title, which only titles scoped to box will contain if conventions are followed. This will also target the title no matter how you refactor the markup inside of box, if the title moves from the left panel to the right etc.

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.


Sorry I meant I don't see the appeal in contrast to using CSS in JS solutions, BEM clearly offers better separation of concerns compared to traditional CSS, but this problem is already solved when using CSS in JS, because you explicitly import the styles you want to apply to an element, having to line up class names in your CSS and DOM is a non-issue as the classnames are autogenerated


Show us a pastebin of your compiled CSS. I can tell you from now your CSS is bloated with the uncountable properties and classes that repeat the same fixes and structures. You can program functional CSS and get better in way.


My experience has been that the extremely minor performance benefits of functional CSS are not worth the extra time and energy you will spend on a multi-person team trying to mitigate duplicated class names and conflicting CSS functions.

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.


I did many BEM projects. The idea behind Functional CSS is precisely that: let entire teams work without having to deal with naming. The project becames ultra-maintainable with the best legacy support.

My experience and all the data I've gathered about performance, even coding the equivalent in UCSS was shocking: 400% render speed improvement. 600% loading resources improvements and radical painting speed. To set you in context: one corporate website from a bank, had an average of 230kb resource loading, we lowered it to 33ms. 650ms rendering, we lowered to 90ms. Painting speed avged 90ms, we lowered to 12ms. If you plan things properly, you can radically improve the speed.

It's true that UCSS doesn't make that much sense for very small websites. Although you will render close to a plain HTML doc for sure. It makes sense when you need to repeat and componetize many things. There's when you gain true power. For example, in our tests, we made another equivalent 590kb uncompressed CSS file to 32kb total code need in UCSS. Compressed was about 12kb against 190kb compressed file. That's how you make great improvements.


I've discovered functional CSS some months ago, and I don't think I'll ever look back. Building everything with simple classes makes it easy to keep things consistent, appearance concerns live firmly in the style layer, and once patterns of classes used together start to appear, I can break the rules a little with SCSS and make classes like "button" ("ps ts cap rc2 box1") for the shorthand convenience.


Once you add all of those classes, it's nearly impossible to add a developer who isn't used to it. It's also really hard for me to read. Tailwind / bootstrap etc - is a total deal breaker for me. I'll just get a different client. https://www.browserlondon.com/blog/2019/06/10/functional-css... I just can't imagine not writing CSS like this: https://maintainablecss.com/chapters/introduction


Specially if you work with reactive HTMl, like VUE or React. It's a win. Even with old MVC frameworks you can work confortably and have inmeasurable performance and development speed. The CSS becomes so easy to read, mantain. Changing things is way faster. Back then I needed to watch so many things to do the job. That's why I lost my OO CSS bias.


But does bloated CSS matter?

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!


It matters.

First, not all users need your huge CSS file, in terms of downloading. Specially when they're on mobile phones and cache is crap.

A ~9000 rules CSS file will load and become COSSM slower than one that has 1000 or 10. It is linear increment. Make a test to see it for yourself.

A bloated CSS is more network time. Therefore, slower loading.

A bloated CSS will contain slower selectors, therefore slower rendering time and painting speed.

When you count all these things, you will see radical speed performance.


Maybe. You need to measure these things and get a feel for the actual performance impact to make informed decisions.

Rule 1 of performance: Your intuitions are not reliable.


Upthread, this commenter did post specific measurements from production projects.


Does download size matter? Why bother with compression or minification?

https://jakearchibald.com/2019/f1-perf/


No. No way. If you're CSS is a problem - then you are doing something really really wrong.


I agree. While I'm in theory in favour of alternatives to CSS, my experience with css-in-jss using the React Material-UI framework has been pretty painful.

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.


I’ve been using BEM for about a week now and my first impression is that the readability of my code has improved a lot. It’s only a small project though.


What made CSS in js harder for you?


So obviously, all of this is just opinion me.

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.


Thanks for taking the time to share all of this. Definitely something for me to review a few times and think about.

For me the argument for was: maintaining a component tree and a style tree is a non-start. Too much for me to keep sense of.

But admittedly I didnt think too much further than that.


I don't think CSS is outdated, it was just never that suited for the purpose people are using it for.

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.


I'll bite: what's different about styling a UI?

UIs are presumably more consistent/less varying than documents, so special cases and cascade overlaps should be less of a thing?


You accidentally apply a global style, and your entire UI is broken.

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.


Those are certainly everyday concerns for people doing UI work, but I'm not sure I see how they're specific criticisms of CSS.

Global is going to mean global, regardless of whatever's managing the appearance, and the only UI systems I can imagine that wouldn't have a problem like this would be those with an entirely uncustomizable global UI presentation.

And for differing stylings inside a specific visual component -- generally, specificity is on your side here, most of the time the selectors involved in component-specific rules will naturally override global styles and you'd only fighting specificity if there's another component specific rule. If that's the case, though, what system would save you from conflicting rules applied to a specific component?


> You accidentally apply a global style, and your entire UI is broken.

That's only a concern if your UI elements depend on global styles, right?

Meanwhile, UI toolkits such as Qt use CSS (actually, Qt Style Sheets) to style UIs


> That's only a concern if your UI elements depend on global styles, right?

No.

   div {
      padding: 15em;
   }
This will affect all of your styles. CSS is a flat global namespace where you fight to style your local components by overriding rules with increasing specificity.


Given the abundance of div elements in modern HTML, a CSS rule to set padding in all of them can only make sense in an unlikely minority of abnormally simple and constrained pages. Setting a huge, fixed 15em padding is also highly suspect.

You need to "fight" only in poorly designed systems; UI elements can pretend to have a hierarchical namespace and avoid all interference with other components, and pages can be designed systematically (e.g. box-sizing border-box vs. content-box, padding vs. margin, flex...) to simplify CSS rules.

div.arbitrary-ui-library-prefix-radio-button-group { padding:0.5em; border: 0.1em dotted rgba(0,0,0,0.3); }

div.arbitrary-ui-library-prefix-huge-padded-box-container { padding:15em; }


> You need to "fight" only in poorly designed systems;

So pretty much most systems, especially general web Dev and frameworks


> This will affect all of your styles.

Your example affects all div elements which are not styled. If you also include class and/or ID specific definitions then your padding setting doesn't cascade and those are not affected. That's the point of CSS.

> where you fight to style your local components

That's not true. Style changes do cascade but they only cascade where the designer intends them to cascade. If a designer specifies that all div components shall use the same padding then you can't complain that all div components are using the same padding.


> UI toolkits such as Qt use CSS (actually, Qt Style Sheets) to style UIs

This statement makes it sound like every Qt application uses CSS. That's not true. CSS is offered as a way to apply corporate branding to an application. I'm not aware of any FOSS Qt applications using CSS.


> This statement makes it sound like every Qt application uses CSS. That's not true.

The applications that are ok with the default style don't need to specify style. Nevertheless Qt is an UI toolkit that supports CSS styling.

> I'm not aware of any FOSS Qt applications using CSS.

And that's ok. Nevertheless I've already worked on a couple of Qt projects that used Qt Style Sheets extensively. In fact, that's pretty much the norm in any non-desktop project.


That's a design decision by the ReactJS. Some consider this a flaw of ReactJS. Usually all CSS stylesheets are not included globally in all pages.

Also, if you need to apply a different style, you can just include your custom stylesheet after the global or base stylesheet. As long as you use either the same selectors or more specific selectors, you will be able to override the previous styles. This is assuming the previous developer didn't make the bad design decision of using !important which usually can't be overwritten.


Separation of structure/content and presentation is great for textual content splintered with a few images, so it shines in blogs, news sites (in theory) and other types of informational sites (like documentation). I can give my blog a brand new look without touching any HTML markup, which is awesome.

This separation does get in the way in certain modern web apps, where content is basically scrambled garbage without proper presentation.


This is not quite necessarily true - I work at a tech giant and we've opted for using scss still & are quite happy with our choice.


Is your company actually building a platform for developers to build apps? Because that's what Apple is doing and they shifted away from using paradigms like CSS.


I work for Apple.


One of HN's wonderful moments :)


CSS is not a paradigm. Whatever workflow you have for styling your pages and apps, it's all CSS in the end.


CSS can certainly be described as a paradigm. It's a model you follow to style things on the web.

It also doesn't matter if it's all CSS in the end. At one particular end it's all manipulating assembly instructions, but I wouldn't call styling pages writing assembly. That is to say the underlying model or paradigm (styling in this case) doesn't really matter if you build an abstraction on top of it that hides that paradigm.


Sure, you're right in that sense, thought I do not agree with the comparison to writing assembly.

The phrase "shifting away" from CSS is what I was addressing my initial comment towards, and I don't believe that using a paradigm on top of CSS would constitute a shift away from CSS... you're still using plenty of CSS rules whether you use styled-components, modules, SCSS, etc.


CSS is absolutely a paradigm. Not the specific style rules that exist in browsers, but the idea of selectors, specificity and stylesheets.

The fact that it's possible to define layout and styling using just style properties is the giveaway.


CSS that affects a components internal layout should be with the component.

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’


If using JSS, you can use a theme for common appearance settings, and use a context that carries that to all components. For example, material-ui uses this approach and I've found it works incredibly well in practice. I've added additional values as needed to my theme and this carries all the way down.

This includes additional/adjusted fonts, colors, etc.


CSS definitely can get in the way with far-distance effects in MVw apps. It tends to not being particularly representative of how you think about and modify the app during development, nor during maintenance. Though you still need media queries since you can't use these and eg :visited etc as inline styles. The reasoning behind this asymetry isn't entirely clear to me; it seems to be a syntactic accident.

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.


> separating stylesheet from layout isn't really a thing anymore

It never was, layout is part of stylesheets. Do you mean separating content from presentation?


I've been saying this for over ten years. Glad the world is kind of coming around to it.

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.


Already addressed earlier but inline styles ignore media queries so you may have missed the entire Web 3.0/4.0/responsive web design etc which occurred in 2012.


You mean changing the layout to be less useful on mobile (or occasionally making the layout less useful on desktop and changing to a better one on mobile)? Yeah, I'm pretty happy to have avoided that one.


I don't blame you lol


Personally I prefer a mix of both. For reusable components, I prefer inline styles. These are things that shouldn't be mutable without creating an exception to the design language. For basic page layout, standard stylesheets all the way. I shouldn't have to know react to make a marketing page that has nothing dynamic on it, but I'd still like to be able to reuse existing components on that page easily.

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.


I don't think it ever made sense.

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.


I agree. I have moved away from using IDs for CSS, though, as have a lot of other front-end developers. I use IDs strictly for JavaScript now. I was a happy user of IDs for CSS for probably twenty years but the transition away from that was largely painless and I don't feel like I lost anything along the way.


to me CSS feels a bit outdated since big companies are definitely moving away from this separation. How does HN feel about this?

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.


HTML isn't about UI. Never has been and never will.

The pain will continue until people understand.


HTML/CSS/JS is arguably the most successful UI platform in the world, so this is obviously wrong. You just want HTML to not be about UI.


Something can be "not about UI" and "the most successful UI platform in the world" at the same time.

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.


Well like it or not but the rise of REST APIs suggests that HTTP is extraordinarily well suited to use as a general interface so it's not too surprising that the related markup language HTML has found similar use as a user interface.


> Things like SwiftUI and React are showing that declarative UIs can be built by tying the style to the layout

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.)


I've written a series of very similar articles, and seeing as some of the ones in this site don't seem to be available yet, and otherwise as another point of view, they may be of interest to anyone looking at this: https://ctidd.com/2017/css-ui-patterns/content


Saw this awesome project on Lobsters. I went ahead and ported these components to generalized, composable Styled Components. There's also an npm package at `every-layout`.

https://github.com/aarohmankad/every-layout


You mean "React Components" right? Nice effort, but please mention that these components are supposed to work with React. If we now use the word "Component" as a synonym for React, you make it look like there are no other frameworks than React.


No, he meant Styled Components, a popular library for styling React components.


I see, didn’t know about this. Thanks for pointing it out!


Out of curiosity, why doesn't the stack layout use flexbox? It seems like flexbox is the perfect fit for such a layout.


Margins of flex child elements won't collapse automatically like regular elements. It can be solved but it would be unnecessarily complex for the simplicity of the layout.


Because it's a just a simple stack. The intent is concistent margins between siblings within the wrapper. What came to mind were paragraphs. Or perhaps images. Or both?


If other browsers besides Firefox add support for the gap property, Flexbox will be perfect for this. The owl approach has some subtle issues, like not taking into account elements which show/hide based on breakpoint.


Pardon my naivete, but wouldn't stack be just a list of divs?


Flex is great for one directional layout within a box. It is not great for two dimensions which most layout is concerned with.


The stack is not two dimensional.


Has nothing to do with what we're talking about.


Display: block fits better because it has been around for more than 15 years unlike flexbox. And flexbox has no advantages in this case.


started reading some of the ideas and got put-off almost immediately. 'margin-top'? the owl-selector? Really? Why do we keep making our life more difficult than it should be? CSS is such a beautiful and interesting tool, yet we still decide to misuse it in trying to be too smart.

( 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 )


> so the usage of margin-top should always be avoided

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).


I was suprised the degree to which selector performance is a negligible overhead in normal use these days.

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.


This is great.

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.


Suzy grids 2 is an amazing tool for ie11 and everything above it. So I can use one codebase for everything.

Yes, it is float based but my code is at the correct level of abstraction.


To me this way to CSS development is outdated. I will never program like this anymore. I only do functional/utilitarian CSS.


NOTE: I think this refers to the approach implemented by libraries like:

* https://tailwindcss.com/

* http://tachyons.io/



I agree, libraries like tailwind.css are such a breeze to work with (pun intended).

Initially they're frustrating, but after awhile you recognise the ease and predictability of styling reusable components.


can you elaborate? (also fotolog is not found)


Yes, fotolog.com doesn't exist anymore but I would gladly elaborate. (full explanation here: http://minid.net/2019/04/07/the-css-utilitarian-methodology/) resume: why go with an OO architecture, when you can use inmutable classes and never again repeat the same properties in your CSS files. In the end, you end up developing faster and you can mantain code easily without having to build the entire UI arquitecture in the CSS. CSS was created to separate style from the content, but also, because back then, HTML wasn't built like we do today with frameworks. Now that we use reactive HTML we can just print inline CSS, but that is a problem, so the functional CSS comes better.


Pardon?


CSS has been a bit of a mess for ages.

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.


I've researched all the major newspapers code. From 1996 to 2019 and all of them grew exponentially in size and complexity. It is how you state it: the arquitectures force developers to do bad code. Unmantainable (most devs change jobs, go and read 9k rules) and websites morph over the years carrying lots of legacy code because it takes too much time to fix everything. That's why functional is superior to everything. The problem: all devs are biased with the OO way. It's hard for them to see the benefits.


Yes, functional CSS goes against current best practices, so people write it off without giving it a try. It's a shame as I think it's the best way of doing CSS at this point. For web apps at least.


Is a single purpose class still a class? Not in the conventional sense - In CSS' lexicon it's a group of things, right?

I've got nothing against the approach - it solves a problem - but it's not how CSS was intended to be used.

CSS modules, CSS components, BEM, heck even Sass and Less fall into the same area of trying to wrangle huge unsorted lists of loosely composed attributes into something meaningful.

So if there is a requirement to bend the rules, the problem is with CSS itself.

Heck, even at the most rudimentary level of organising your CSS falls foul - the accepted best method for sorting attributes within a selector anybody seems to have come up with is alphabetical, which feels weird because it weaves layout, typographical and aesthetic behaviours. Why alphabetical? Because nothing else makes much sense, ...so it wins out by default?

I still maintain CSS is a mess from top to bottom.


Please, elaborate on the first statement. In CSS a class is a class, we're not tied to group things. Original CSS wasn't group purpose, mainly due the lack of properties, you could see more single or a couple of properties per class.


I'm taking about classes with an enforced 1:1 relationship with a DOM node, via a unique computed className.

Since there is no requirement for a cascade for this, you've effectively made an ID out of a class.

All the reasons styling off IDs isn't ideal in the traditional CSS metaphor still apply, specificity, verbose stylesheets, etc. But now it's defined as a class too.


I would not call them "best practices" anymore, since those practices only bring a notable decrease on loading, rendering and painting performance. As well a bloated architecture in the short term and a huge file size.


Having been doing full-stack for over 15 years now, I have never seen the owl selector before. It's almost a perfect solution to a problem I regularly have.

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 * +


It's worth noting that * is incredibly inefficient, especially near the front of your selector, because of how the browsers generally handle element styling. It may be better now than in the past, but it's best to avoid it for the most part.


The knowledge contained in the articles is very good but I got the feeling that it was written for an audience that already undertands the problems being solved. The Stack for instance is written in a language that only really makes sense if you've spent a lot of time with CSS and contains some extraneous paragraphs. I only mention this as the problems and solutions being explored are very valuable to learn but I think it could be written simpler and more succinctly so that meaning isn't lost for new-comers.

I'd be happy to contribute if it was open to suggestions.


This kind of critique is applicable to all sorts of specialized writing. The flipside is that an article of this caliber (And it is indeed a very useful and well written set of guidelines for the intended audience) is not truly relevant to the layperson or an absolute beginner -- he lays out common problems and frustrations that people who've ever tried to layout a moderately complex website would have encountered, and presents some good solutions for them. If you haven't worked in the field and encountered these sort of problems, then an article like this is simply not relevant.

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.


Bear in mind the tutorial is prefixed "Relearn..."

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. Do you find this is the case? You need to be an expert at both roles plus have a third skill connecting them together.


    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.


I think there's often a leeway given to the full stack dev that they have strengths and limitations. I haven't got to the point where I could compete with the true / good front end dev with my skills.

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...


I've been a backend developer for years and at times a frontend developer.

I've applied to a few full stack positions and the amount of specific knowledge in various topics they require seems much greater than either role separately.


When hiring or interviewing we tend to build up a big list of skills so the job looks impressive and attracts talent. Don't take the requirements too seriously.

Ideally the person doing the hiring is just measuring your knowledge. But I know many interviewers just try to eliminate candidates.


This website is one of the accessiblest things (for screen readers) out there. I have never seen alt text for layout images. This is well beyond amazing.


Uh huh, what about "the vertically centered div" and the ever important "span vertically centered within the parent"


There is more than way to do all of these layouts. I don't have time to learn all of them, I just want my content to look great on all devices. I also want to stick to the specifications of HTML as it applies to all the browsers that do HTML5 - so no Internet Explorer. Sticking to the specs means no hacks and the likelihood that someone can make sense of my code in ten years time and not think 'why did they do this?'.

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.


> if I am using the right elements and pay attention to the structure of my content it just naturally styles itself with CSS Grid

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.


I think the point here is that if you use semantic elements, you don't need to use classes to differentiate.


What I have learned just from having a go is that document outlines matter too, so I just think of whatever I am writing in terms of sections, articles and asides. I don't actually ever think of adding a 'div', there is just no actual use case for them.

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.


If seems like you discount portability as a concern, and if that's appropriate for your use case, that's a fair decision of course. But there are many use cases for which that's a priority.

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.


When it comes to portability I find that a class for the component is all that is needed. So that is at the root element of the component and with everything inside classless. So '.component > nav > ul' might be how I would style navigation inside the component, knowing it would not inherit styles from the body defined classes for header/footer navigation.

The BEM type of examples you will normally see will have everything as a div, I just avoid div elements not out of some prejudice against them but because I am out of the mindset to think to use them.

A lot of what I am saying here does fall apart on over complicated commercial projects though where the CSS is 'add to' and you can't just strip everything out to do it stupidly simplified.

I am also not a fan of monolith stylesheets with resets and frameworks adding thousands of lines of CSS. The idea that you should need 30000 lines of CSS for a product page is just silly, but even some of the best websites are doing that sort of thing.

In one of my pet projects that I am not quite happy with yet (wording could be better), I create a lot of content from JSON data using templates done as 'template' the element. The approach of using simple selectors works well when it comes to taking a template, changing elements within it such as the title and adding rows of data to it. I have struggled with over complex toolkits that create stuff, e.g. the Wordpress Gutenberg editor, but I find vanilla javascript (no compiling) with full feature HTML5 (all the elements) and the compound selectors work great. At one level the rest of the world is way ahead of me on these mega complex build tools but then I wonder if they are really needed.

Anyway back to it!


Good points, seems using semantic tags makes a lot of sense.

Just a question, is article part of a section, or section part of an article ?


Do you have any examples as a Gist?


I think I should. My actual commercial work is still done with old fashioned HTML, my first couple of pet projects done with the new way of using HTML5 don't have perfect document outlines as I was still holding on to the old ways of doing stuff and are not my best work. Only now am I fully in my stride on doing actual lean HTML with a couple of projects I haven't fully finished.

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!


"Web browsers helpfully apply default CSS styles..." Totally disagree with the idea that this is 'helpful.' Pretty site though. I think there's some good stuff here - but it's not how I'd teach it. Side-note: I love how wappalyzer says 'zero technologies detected.' That's rad. "Each layout in Every Layout is intrinsically responsive." Everything is intrinsically responsive before you force it not to be. Big respect for tackling this though. Lots of good stuff and just a bit of maybe not great stuff.


What’s the best resource (book, videos etc.,) to learn css these days?


Hey once you're past the fundamentals check these two cool games out. They teach how to quickly grasp the most difficult parts of CSS - the layout.

https://flexboxfroggy.com/ https://codepip.com/games/grid-garden/

I wish all learning was this fun.


Wow, that grid-garden game is great.


Here's original link for grid garden, and it doesn't need login to play https://cssgridgarden.com


I'd be curious to know what you consider the fundamentals to be.


I have heard lots of good about "CSS in depth" by Keith J. Grant. It explains why and how CSS does things, rather than just telling you to do one thing for that use case, and another thing for that use case. It is meant for people who already know a bit of CSS, but it wouldn't be too hard to learn the basics of CSS first then read this book. Also, it is free online on the publishers page, which is extremely generous of him and the publisher.

https://www.manning.com/books/css-in-depth


It's probably not for everyone but I just read the specification [1] last week. It is probably also worth noting that I did this to get a better understanding of some details and not for initially learning CSS. But those are mostly easy to read specifications and I think one could use them to initially learn CSS.

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.

[1] https://www.w3.org/Style/CSS/current-work


I commend you. I am with Kyle Simpson (of the You Don't Know JavaScript fame) here—too often people don't even try to learn about the stuff they are using and are surprised by the behaviour which is clearly stated in the specification. This is true for JavaScript, but this is especially true for CSS. I think it is one of the least respected technology, devs don't spend much time and effort in learning it and then complain about it being a mess and not making sense. So if anyone is tired at throwing stuff at the wall and seeing what sticks just go and read the specs. It's much easier now than back in the days of IE5/6, no grid and no flexbox.


That was brave. I learned how the box model works from the specification.



CSS is completely dependent on HTML. If you write poor HTML - then you've already shot yourself in the foot. If you can't learn them together - then it's really hard. People don't learn the different display types / or positioning, and then they freak out when they can't figure out why a margin-top isn't working on their inline element. I've never met anyone I consider to write decent markup or styles in any of my jobs. This is pretty good: https://maintainablecss.com/chapters/introduction/ - but it doesn't teach you CSS. It teaches you how to write maintainable CSS. MDN is the best we've got (so far)


An updated version of CSS: The Definitive Guide was released relatively recently, and I think is fairly good.

(https://www.amazon.co.uk/gp/product/B076HZSWTM/)


https://developer.mozilla.org/en-US/docs/Web/CSS

is all anyone needs except the standard itself.



I'm not sure if the creators will read this, but on https://every-layout.dev/rudiments/axioms/

> 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".


>https://every-layout.dev/layouts/cluster/

>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


It's still in production meaning: they are not available yet, they are being written.


Another way of saying that would be that they are still in "development"


Poor quality articles. They use flexbox and provide no fallback for older browsers. They could use at least non-responsive layout for desktop resolution for older browsers. Probably the reason why they didn't do it is lack of knowledge of CSS.


Flexbox has been supported by all browsers for years now, even by IE11. What on earth do you need to support if you cannot use flexbox?


Caniuse says that IE11 has a lot of bugs regarding flexbox. Firefox supports flexbox only since 2013-2014. So it would make sense to add a simple non-responsive fallback for older browsers.

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.


caniuse.com also has the combined global market share of IE 6-10 as being only 0.46%, which is completely insignificant for most websites. And I've personally been using flexbox on IE 11 for years with very few issues.

> 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.)


Global market share stats are applicable for global target websites. Consider any medical equipment company for example - their clients will browse the catalog from archaic, unmaintained PCs they have laying around.

Always get data about browser market share from your client if they have it, otherwise you're simply in for an uncomfortable surprise one stats start coming in.


Win7 and IE9 are both EOL in six months. Makes sense to drop in new articles.


HTML/CSS was designed to be forward/backward compatible and not to be written only for version of Safari installed on dev's macbook. This is against the spirit of HTML.


If I understand right, you are suggesting it is "against the spirit of HTML" to write CSS that isn't backwards compatible... infinitely? You have to draw the line somewhere, right? An ancient enough browser won't support CSS at all. Using only CSS that would be supported by a, say, year 2005 browser would also be pretty limiting.

You can choose to do that if you want, but I think your opinion about the "spirit" is a minority one.


That ship sailed the day people first started using HTML for page layout in general.

The spirit of HTML was not adequate to meet requirements, so the spirit has been upgraded. Pray all you want, it's going to be upgraded further.


Don’t believe that argument can be used in favor of IE, which was never standards based.


I haven't had any trouble doing flexbox for IE11. I always make sure to test in IE11 because of the caniuse warnings; I have very rarely run into any problem with IE11, maybe once or twice, and they were easy to work around problems.

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.


If you need to still support IE 8&9, there are pollyfills that will add flexbox support to them. They aren't as quick as native, but they still work.


You may be surprise to know who is Heydon who co-author in the article.

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.


Andy Bell? Lacks CSS knowledge? That's a bit over the top.


Maybe their target audience doesn't primarily consist of entry-level devs relegated to maintaining legacy eCommerce web properties and back-office portal/intranet systems?


The code examples are overengineered. For example, the code generator for stack uses rem units and CSS variables, while it could be written without them and have better cross browser support (and the code would be easier to read and maintain in long-term perspective). The author just wants to use modern CSS features without clear rationale for this.

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.


This is plain FUD, sorry.

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.

https://caniuse.com/#search=rem


I find your counter-argument against rem units very weak.

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).


> 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.

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?


A website that is maintained in a long term will be worked on by many people, and CSS will become quite large and complicated. So using the simple constructs like pixel units is better than using rems that create implicit dependence on main font size. This way there are less chances to break something in one place when editing code in other place.

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.


If you hard-code everything in pixels, you have the same implicit dependency as with rem. It's a design, after all! Things have to "fit together". You're not changing every element's font size to an individual value and on a whim.

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.


Correct me, but I can tell what 16px is, not 1rem. 1rem can be 16px, 18px, 2000px. When you see tons of relative units, you need to doble check what it's going on. With pixels you see explicit values, so no double checkings.


Yes, but a typical change request would be something like "make this menu font size larger", and in this case having menu independent from other parts of the page is better. Also, if you build a framework with variables, dependence on root font size, it would be complicated and most devs won't like to spend time learning it and thinking how to solve their task within it. Simple is better here.


If you code everything in pixels, your site only will look good on your particular screen. This has become so much of a problem that browsers now use a ‘standard’ pixel that is divorced from an actual pixel. I also find sites that do everything in rem/em more assessable as the padding also scales if they have a increased font size due to low vision.

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.


> I also find sites that do everything in rem/em more assessable as the padding also scales if they have a increased font size due to low vision.

If you use Ctrl +/Ctrl - for zoom, then everything scales proportionally regardless of whether you use pixels or rems. You are trying to solve the problem that has been already solved by Opera, and later by other browsers more than 10 years ago.

> Also, hardcoding things instead of using variables makes things harder to maintain.

In my experience, it is the opposite: simple code without implicit dependencies is better. Because the typical task would be to change one part of the page without affecting other parts. With a simple code, I would use DevTools to change the CSS rules and then I would move the changes manually into CSS file. But if the site uses some complicated framework with variables and rems, I will have to spend time learning it, see where is a variable defined, what can be affected if I change it, etc. It just takes more time and nobody of the devs will want to learn your custom-made CSS framework.


Using Zoom for reading is less ideal for long term use as it generally forces you to horizontally scroll, where as increasing font size reflows the page, so only vertical scrolling is needed.


In Chrome, Ctrl +/Ctrl - reflows most text.

Like most things on the modern web, it is complicated. There seems to be a way, which I never noticed before HTML5 hit, for the web page to specify that certain text will not wrap, but rather will just run off the right edge of the viewport if the viewport is too narrow, but it is not in common use.


> padding also scales if they have a increased font size due to low vision.

rem: automatic for the people


IIRC the standard pixel was always divorced from the real pixel. Or at least for a very long time.


>A website that is maintained in a long term will be worked on by many people, and CSS will become quite large and complicated

Non-sequitur. It could also become smaller and simpler.


On the topic of rems, when using them for layout, you'd use a body font size rather than the root element's font size to control the size of text in your page.

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.


It is not as simple as just replacing pixels with rems. Do you test your markup with different root font sizes? Do you add special rules for cases when the font size is too small or too large? Unlikely. Then you better not pretend that you support scaling the fonts using browser settings.

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.


If you build sites that can support arbitrary viewports, extrapolating to arbitrary scaling factors on a given concrete viewport does not create an explosion of scenarios to manually test -- all you need to know is that your scaling works, and if you always build your functionality responsively, the scaling and responsive layout together just work. (I'm talking about building the whole layout with rems, not just using them for font sizes. For the latter, I'd agree with you that it's brittle and falls apart quickly.)

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.)


Rem is great. It allows uniform scaling of all UI elements under a parent along with them font size.


Rem is great. px work well. Both can work and not work for different reasons. The extremes on this issue remind me of spaces vs tabs.


Where is this used? If a user wants to make everything larger then they can use zoom in a browser that works with any units (except for vx, vh, vmin, vmax that break zoom).


Designers or developers.




Guidelines | FAQ | Support | API | Security | Lists | Bookmarklet | Legal | Apply to YC | Contact

Search: