Hacker News new | past | comments | ask | show | jobs | submit login
How to center a div in CSS (joshwcomeau.com)
445 points by joshwcomeau 9 months ago | hide | past | favorite | 258 comments



There are a bunch of comments commenting on other comments so I'm going to join in.

These comments are largely talking about how centring is hard from an implementation standpoint and can mean different things. Sure, but the whole "CSS centre meme" is just "How do I put one element dead centre within another". I can't point to data to back this up, but I'm pretty sure that's what 99% of people mean when they ask "Why is centring so hard?"

For those of us who grew up with GeoCities and AngelFire etc, the reason not being able to easily do this felt so ridiculous and why it was hard to buy that it's hard to implement is that we were able to do this no problem with HTML, and still can!

    <table>
      <tr>
        <td width="600" height="600" bgcolor="yellow" align="center" valign="middle">hello</td>
      </tr>
    </table>
That puts the text "hello" squarely in the middle of a 600x600 yellow box [0]. This worked in the 90s. I know nothing about the implementation of CSS, but surely you can understand the annoyance of been handed a new tool, told it's better, yet wasn't able to do such a standard thing lots of people were already doing. It's a big reason I didn't listen to the dogma and kept up with table layouts into the late 2000s.

PS, maybe it's Stockholm Syndrome, but I love CSS FWIW.

[0] You actually don't even need the `valign` which surprised me, at least not in chromium... I'm not sure if that is a recent thing because I haven't actually written code like that in around 15 years.


You've been able to do exactly what you describe (i.e. putting "hello" squarely in the middle of a 600x600 yellow box) with CSS since its first incarnation, with e.g. the `valign` HTML attribute corresponding to the `vertical-align` CSS property on an `inline`, `inline-block` or `table-cell` box.

But then again, in my experience many of the people who wax poetic about just using tables and/or complain about how CSS is limiting and confusing...never actually put in much of an effort to learn how it works. At least the article's author is self-aware about this.


>> You've been able to do exactly what you describe (i.e. putting "hello" squarely in the middle of a 600x600 yellow box) with CSS since its first incarnation, with e.g. the `valign` HTML attribute corresponding to the `vertical-align` CSS property on an `inline`, `inline-block` or `table-cell` box.

Notably not a `block` element like a div or p - which is what most people are going to use as a container.


...the entire point of CSS is that you can style any element (almost) however you want, which includes changing how it's laid out by the browser.

Case in point - unlike with HTML alone where `valign` only works on table-related elements, you can set `vertical-align` with a compatible `display`/layout algorithm on a div, p, etc as you wish.


In 2000-2010 not only I was a fullstack developer, but also had to write CSS and HTML code for the websites I worked on often.

I remember that as an extremely painful experience. I can't remember all the details, but I remember that until flexbox and grid were implemented, everything CSS related was a pain. I vaguely remember that until 2008-2009 (maybe I'm off by 1-2 years) something trivial as rounded corners also was a pain.

I also remember that about 80% of the CSS pain was caused by Microsoft Intenet Explorer 6.0. It was complete garbage when dealing with CSS and Javascript (I was working with huge JS codebases at the time). But nobody in the web world could ignore it because it had a huge market share. I hate that browser and Microsoft with passion till this day. So many hours, days, weeks wasted to make everything work in a browser that wasn't updated by MS (why spend money when everybody is using it - they even fired the team that worked on it) and had a very "specific" implementation of Web standards.


You’re 100% correct in your recollections and the frustration of using CSS in those days contributed to me not wanting to keep working on the front end at all. And yes, F MSIE all the way to hell How many thousands of human lifetimes were spent trying to make that piece of crap work.

I still don’t know flexbox because I had given up by then. Thankfully I can have ChatGPT help me these days if it comes up, but thankfully FE is not really a part of my normal job.


If you want to relive hell, work on HTML emails. Yay for outlooks ie6 renderer :(


I remember setting up rounded corner PNGs with IE compat shims because it couldn't handle transparency otherwise..

I also switched away from frontend dev because of this silliness eventually.


You aren't wrong, but I don't think it was the case of not doing diligence. I welcomed CSS and started using it when it came out, though it was certainly painful back then (as siblings have pointed out) and I don't believe it would be a good faith argument to say otherwise. I was aware of `display: table-cell` but it always felt like a hack. I'm well of the irony in that statement, but if I'm going to call something a table cell, why not use a table? Regardless of how that sounds, that's how people think, especially 19 year old me! Furthermore, the name was far too technical. People who had little-to-no experience with table layout weren't going to search for "table" when wondering how to centre something.

In any event, the main reason I stuck with tables (and this of course was only in person projects) was because CSS didn't have a viable way to do layout until 2017. Semantics aside, I still view table layouts as superior to floats and clearfixes. I was terrible about thinking about accessibility back then, of course, so I'm not sure of the impact there.


> You've been able to do exactly what you describe (i.e. putting "hello" squarely in the middle of a 600x600 yellow box) with CSS since its first incarnation, with e.g. the `valign` HTML attribute corresponding to the `vertical-align` CSS property on an `inline`, `inline-block` or `table-cell` box.

display: table-cell came along with CSS 2.0 (1998), and display: inline-block came along with CSS 2.1 (2011).

Unfortunately, there were huge amounts of CSS 2.0 that weren’t supported by Internet Explorer 6 (2001), and there was a five year gap until Internet Explorer 7 was released in 2006, which didn’t improve CSS support much (basically just support for a few selectors was added). It took until Internet Explorer 8 was released in 2009 before it supported the eleven-year-old CSS 2.0 properly. And after that point, web developers had to wait years before enough people had upgraded that it became possible to drop support for Internet Explorer 7 and below and start relying upon display: table-cell etc.

So even though CSS had display: table-cell in 1998, web developers couldn’t actually use it until after ~2011 or so. But still, that was 13 years ago now – time to stop beating the “Centring in CSS is difficult” drum.


Yeah - I was squishing together the current state of things with the original. Maybe a clearer way to phrase that would have been that CSS has been able to vertically align elements like `valign` on a td does given a compatible display from day one, with the compatible displays starting with `inline` and eventually including `inline-block` and `table-cell`.


Sure but we were told to move from tables to divs and "just use table-cell if you want vertical align" was not a great story nor was is discoverable to those had no prior context of table layout.


>n my experience many of the people who wax poetic about just using tables and/or complain about how CSS is limiting and confusing...never actually put in much of an effort to learn how it works.

I think the big issue in the 2000's was cross compatibility, and how seemingly simple elements on one web engine simply wouldn't work or look right in another. IE 6 was infamous for this. Tables were one of the few consistent elements, could be dynamically generated with ease, and simply feels easier to think about from a designer POV

I think that misalignment (no pun intended) is what lead to the huge snowball that is using frameworks upon frameworks to solve issues that some simple HTML/CSS should have solved. By the time the web engines evened out (and IE died) and CSS got better options, the damage was done. JS ruled the landscape.


in my experience many of the people who wax poetic about just using tables and/or complain about how CSS is limiting and confusing...never actually put in much of an effort to learn how it works

As somebody who was actually there back then your opinion reads as arrogant and condescending. Do you really think the entire industry just did it wrong for decades? That people did not frantically search for an easy solution for this silly problem they faced constantly? You'd do well to learn to be more humble.


Having also been in this industry for two decades, you haven’t noticed the amount of wrongheaded groupthink that leads the entire industry astray with flashy marketing for the latest ill-conceived toy for both management and engineers alike?


Yeah, this industry seems particularly prone to it. Do you not remember the 90s and early 00s, where most of the industry was utterly convinced you needed unreadably small body copy and splash pages? Or how about CSS in general? I must have heard “you can only use CSS for boxy designs” a thousand times before Dave Shea got fed up and created CSS Zen Garden to conclusively prove them wrong. The number of times I’ve seen the majority of the industry believe something completely dumb and then figure it out 5–10 years later is insane.


I have, but in this case it was truly necessary to do all the disgusting stuff like using Javascript to center stuff, because the content width had to be determined in hindsight. All suggestions in the article use features that came out in the late 2010s that solved this.


The entire industry did, in fact, do it wrong for decades.

The problem was never that CSS - a DSL that exposed more of the browser's layout and painting engine than HTML did - was somehow less capable than HTML alone at implementing the same design.

The actual problem was that the requirements of designing for the web changed very rapidly. Take GP's example of text centred in a 600px yellow square; again it's not that it was soooo hard to achieve that specific layout with CSS. It was that they were trying to accomplish layouts a lot more complicated than that, often without breaking those layouts down well enough to be expressed in terms of the available layout algorithms. The longterm solution to this was of course for browsers to provide implementations of more advanced algorithms (like flex and grid) to match more advanced layout requirements, but that process was dragged out for far too long and eventually landed in a far too fragmented manner - a massive mistake.

And on top of that, it's not as if the existing layout algorithms were particularly incapable; on the contrary, they are well documented and you can get very far with them alone. So many questions ("how do you center a div??", "where are my margins??", "why isn't z-index working??") have answers that are quite apparent if you're familiar with the spec and thus understand what the browser is actually doing when it lays out your elements. But how many devs even know that e.g. stacking contexts exist, to talk of when they are created?

It's not as if it's even their fault, it's yet another thing that basically the entire industry did wrong for years. How many web design/frontend tutorials really explain anything about the CSS spec or about how UI rendering works in general, as opposed to just shoving arcane styling incantations at learners to cram? It's a failing of the industry that even today you have to go quite a bit off the beaten path to actually learn CSS (and HTML itself, while we're at it). Imagine if we taught any other language in the same haphazard manner! Just because they aren't technically programming languages doesn't mean that they're not worth proper instruction.


If you look at any of the suggestions in the article, each uses at least one feature that came out in the late 2010s. Add a couple of years until initial bugs were fixed (which were there), and until browser adoption is high enough that older browsers can be ignored.

Back then I could whip up a dozen centering solutions, but not a single one that worked across all browsers in all cases. Tables just worked.

You're so wrong about the history that it makes me assume that you started webdev after this compatibility mess was fixed. It was truly disgusting. If anyone had found a solution back then everyone would have slurped it up immediately.


Ha, ya you're right. My memory on table-cell was fuzzy and didn't bother looking into before making some other responses. IE 6 and 7 had no support for it and Firefox had partial support until 2008. I'm just looking at caniuse, of course, I don't remember what Netscape supported.


I see overlapping text among a smorgasbord of other mistakes on the New York Times front page. Presumably they have the resources to hire top designers from this “industry”. No, I have no problem imagining that they did things wrong for decades.


I agree with most of your comment but my sibling commenter isn't wrong. I certainly think we all do do things wrong. I mean, someone put JavaScript on the server after all ;)


> corresponding to the `vertical-align` CSS property on an `inline`, `inline-block` or `table-cell` box.

I can't believe I didn't know about this until now.

Before flexbox and grid, I don't know how many times have I written `position: relative;` on parent, and `position: absolute; top: 50%; left: 50%; transform: translateX(-50%) translateY(-50%);` on the thing I wanted to put in the middle (vertically and horizontally).


Ya, I remember reading tutorials that suggested this. It was a very confusing time.


Works in Firefox, too, without the "valign" attribute. Though I would not rely on auto-layout behavior in general since I've always seen subtle differences across the three major browsers whenever using tables without a fixed layout.


Nice article, the comments here are kind of amazing for a nominally technical audience. It is almost as if people have no idea how difficult automatic page layout and formatting is. There are literally PhD thesis topics on it[1]. And to expect that complexity to be abstracted away into some sort of simple "do-what-I-mean" expression? That just isn't going to happen.

Go look at Gwern Branwen's web site[2]. That is art. But the trick is decide how you want the site to look and then constraining your written material to be expressible in that style.

I've been looking at web page layout since 1995 when I joined a startup that was doing the "first magazine on the web about Golf!"[3] When the Zen Garden folks did their web site and started the 'A List Apart' mailing list which is now a website[4] it really helped me understand just what one was up against if you wanted to produce web content that rendered nicely on a wide variety of projections. And yes, the term projection is intentional because the function of going from semantic content to presentation on a screen or paper or other flat surface of finite size, is a mapping (or projection) from a native space into the rule set of the destination space. That rule set consists of both physical constraints (pixels per inch, total pixels horizonally and vertically, color capability) and software constraints (how much of the underlying capability can the browser software that is currently running express). Not to mention that every browser wants to do their own special thing.

So yes, CSS is a "hot mess" for people who decide one day "I'm going to build a web page from scratch." And yet, that mess is really just an abundance of choices rather than constraints on what you can do. The process is the same for everyone, find the tools that help you achieve the results you want and then package your material into a form that you can easily convert that into that look.

[1] https://scholar.google.com/scholar?hl=en&as_sdt=0%2C5&q=thes...

[2] https://gwern.net/

[3] It was called Golfweb and eventually ended up being part of CBS Sports apparently (golfweb.com sends you there)

[4] https://www.alistapart.com


Hi Chuck, Great points. FWIW, your tenure with web layout has me beat by about 3 years (1998). In all my relevant experience, the materials at "Every Layout"[1] remain unparallelled. Highly recommended.

[1] https://every-layout.dev/rudiments/boxes/


I don't know I spent a year using "Hotdog" and another three using "FrontPage" so those really don't count as years spent "getting better" :-)


Huh! Yes, yes, Hotdog[1] was what got me started with HTML. It came in a CD with a magazine that was about a month late to a town with no Internet in mid 90s.

1. https://en.wikipedia.org/wiki/HotDog


Haha, I remember being really, really excited about ditching FrontPage for DreamWeaver.


Dreamweaver and Fireworks, oh my.


Finally, someone else on the internet that remembers using Hotdog! Good old Sausage Software… Thanks for the nostalgia hit.


The problem with css is almost entirely self inflicted, though. Yes, layout is hard. Why make it harder by aiming for the model we now have? Specifically, why aim for one major model that will fit all pages? Usually done with another sysipheon aim of automatic layout recalculated every page.

Combine this with the amusing goal of targeting any and every size of window. Why would anyone think that is doable?


it is not only doable (trivially so for most static sites) but also the only appropriate model for delivering websites/software.


Most static sites don't have hard layout concerns?

More amusingly, most static sites did absolutely fine using tables.


Why don't we have completely separate styling systems for mobile devices, widescreen devices, vertical monitors, tablets, and billboard displays? Because that would be a bigger nightmare to deal with than CSS.

I like that when I visit a web page on my mobile phone, it loads regardless of whether or not the site owners hired someone to build a completely separate interface. And I like that when I design interfaces for phones and for large screens, I don't need to learn 2 languages to do it. And I like that when I stack two browser windows next to each other on a 1920x1080 monitor they resize and I can read both of them.

When people say that they don't want to worry about multiple screen sizes in their layout, they mean that they want an interface that works on one screen size and ignores everything else. And that would be a huge loss for accessibility and innovation if the web pushed developers in that direction. The reason it would be simpler for people to work with a more targeted language is because they wouldn't build the other interfaces at all. They'd learn one language, target one device that their most predominant customers used, and then we'd have a mobile Internet and a desktop Internet and they'd be separate things with no expectations that sites would work on both devices.

----

And I think this sort of gets to the complaints about complexity in general, because the complexity of this UI design is reflecting a reality that good interfaces are adaptable and people have multi-faceted needs from their software. Even on desktop, people use different screen resolutions, they scale fonts, they mess with layout. And there's this subtle idea behind complaints about complexity that when you dig into it is not actually "why do I have to target so many devices" but is really "why do people use so many devices? Why isn't the world more uniform, why on earth are people changing their screen resolutions, what's wrong with them? Why can't they just decide on a device and stick with it?"

But good UX design is about designing for the real world, not for a hypothetical standardized human, and in the same way that cars need adjustable seats and can't just say "well on average everyone is this height and width", good UX acknowledges and responds to the idea that software and content are delivered in multiple contexts.

Of course that's a balancing act, it does make interface design more complicated, and it's not something we can do perfectly. But it is a balancing act, it's not a problem we can solve by saying "heck it, everyone needs to stop buying HDPI laptops." I mean, we're not all Linux developers, we can't all just pretend that touchscreens don't exist ;)

The same exact complaints show up with the extensible web and with progressive fallbacks in general. It is real annoying to build software that degrades nicely depending on what hardware support someone has and what features they've turned on and off in their browser. But it's also a better way to build software that better reflects how software is used in the real world by real people.


A problem is that none of the arguments you are offering are bad, logically. It feels very appealing to think you can build a system that would solve "laying out text" for all time.

For me, what they lack is evidence that stands any stronger than video games. Specifically, I've played different games on various screen sizes and orientations that largely work as you would expect. They are not perfect, of course, but they work better than most web pages seem to. And they do that, largely, without the same reliance on something like CSS that web pages need.

More, it isn't like we weren't laying out billboard displays long before the web came to be. Nor is it realistic that billboards have at all the same concerns that a pocket sized phone will have. At large, you shouldn't even use the same fonts between those options. Heck, taken farther, a billboard can hold a slogan, that is about it.

This would be the same as if you tried to use HTML/CSS to make a poster for a movie. Which, sure, you can make a bit of an effort with it. I just don't see it being any better than letting a designer or probably an automated system layout several standard sizes with the standard type in the standard locations.

Pulling it in, I'll be delighted to get proven wrong and find that we have converged to a great abstraction for laying out content. I, of course, do not /know/ that it can't be done. I do pull my hair out at the amount of effort people will go to in order to have the system layout a set of divs, when most designs could probably have done a lot of that math up front and worked with far fewer nested elements than we seem to typically see.


Good layout is simple. But can it be flexibly done without a good sense for abstraction and math? No. I mean, just look at the hot shit that is Tailwind, that's what people come up with while fighting abstraction.

CSS was a mess, but together with React is now the best language for building GUIs. You can build up any abstraction you want in React, even

    <FullScreen><Center>Hello World!</Center></FullScreen> 
In fact, that's what I did over the weekend for my Electron desktop application, writing my own little library of components, including tabs and treeviews, using only CSS and React and no third-party libraries apart from that.

You already have been proven wrong. You are just not ready to accept the proof.


> CSS was a mess, but together with React is now the best language for building GUIs.

People should stop saying this lie. To di so, they should try and look outside of the web for even a nanosecond.

Even Turbo Pascal from 1990s is a better language for describing UIs.

The "best language for building UIs" chokes on less than 1000 elements on a static page: https://pbs.twimg.com/media/GF__tHjXgAAZGUA?format=jpg&name=...

Compare that to an actual UI: https://cdm.link/app/uploads/2023/11/CleanShot-2023-11-15-at...


So, a couple of issues:

A) Out of curiosity, is that "actual" UI screenreader accessible and does it work on mobile devices? Does it work with touchscreens? Can I scale the text? Maybe it does, I don't recognize the program off the top of my head. But I don't assume that by default.

And very often this is just the same argument over and over again. "Check out how cool the thing is that I can build when I assume that you'll be using a widescreen desktop monitor with a mouse and keyboard in the full screen." I mean, great, that's very cool, but I'm glad the the web doesn't allow you to make those assumptions. It's a better platform for forcing you to care about more stuff.

B) You can absolutely get more than 1000 elements on a static page, it's not that big a deal unless you're doing something weird. Of course, if you are putting 1000 elements on a page, you might take a step back and ask yourself why you're doing that because giant pages with thousands and thousands of nested elements are hell for screenreaders. You want to update a thousand pieces of the DOM at the same time. Well, OK, let's ask for a second whether that's actually good interface design. I would argue maybe it's not?

I make this point a lot on HN, but if you can't describe your interface using pure text, you don't have an accessible interface, period. And to rephrase point A, you're correct that if you don't worry about that, you can make very complicated interfaces that are extremely performant, and wow am I glad the web forces you to worry about that.

C) People have a fundamental misunderstanding of what the DOM is and how it should be used, in part influenced by treating the DOM as a markup tool rather than as a render target -- but suffice to say, there is nothing about the interface you're showing me that makes me think it's not doable on the web. Some of these visual components you might jump out and use canvas for -- that's not violating the spirit of the web, the DOM is your user interface, and a bunch of nested DOM elements that simulate a slider using div soup is not more accessible or semantic or maintainable than an actual native browser slider with accessible controls that you throw a canvas element in front of.

The thing that would be hard about building this interface on the web is I would have to care about what happens if the font size changes, and I would have to care about what happens if the user opens the app on a phone, and I would need to care about tab controls and turning this interface into an actual hierarchy, and I would have to think about touch screens, and I would need to have higher standards for my interface design than just "how many elements can I fit on a screen at the same time?".

And again, I am grateful every single day that the web forces designers to think about that stuff.


Your question stem from a few assumptions that you consider inviolable, so I'll go through them one by one

- that all software has to work on mobile

This is a fallacy. Not all software has to work on mobile. More over, mobile-first approach is exactly the wrong approach for a lot of software.

No, the software in question will not work mobile. Because it's a screenshot of Ableton Live, a professional DAW specifically made for desktop and for manipulation with mouse and keyboard.

It doesn't mean that the web is somehow superior here because "it can work on mobile, too". Not for complex UIs, for the exact same reason: screen sizes and interactions on mobile are completely different from desktop screen sizes and interactions. The simpler the UI and interaction, the better it works across desktop and mobile. See, e.g. the stripped-down versions shipped with SwiftUI/Catalyst.

- that complex dynamic UIs like the one in the screenshot can actually be done in DOM, no problem

No, they can't. And you immediately list several reasons: "because giant pages with thousands and thousands of nested elements are hell for screenreaders" and "You want to update a thousand pieces of the DOM at the same time. Well, OK, let's ask for a second whether that's actually good interface design. I would argue maybe it's not?" and "Some of these visual components you might jump out and use canvas for "

All this translates to: no, you can't make the same interface in DOM.

1. Complex dynamic interactive UIs are a hell for screenreaders regardless of technology. And there are no good solutions there.

2. Updating tens of thousands of elements is not an issue even for mobile. Games routinely update tens to hundreds of thousands of elements in a matter of milliseconds. If it's a problem for DOM, it's an indictment of DOM.

Updating even hundreds of elements is quite an ordeal for the browser. Professional software will easily update hundreds (or indeed thousands) of elements in its UI at any point without breaking a sweat. If that seems challenging to you, that's the problem of the technology you use and defend, not of the UI.

3. If you need to "jump out to canvas" to implement certain stuff, then you failed both your claim about screenreaders (canvas is 100% inaccessible) and your claim about "doable in DOM" (you wouldn't have to jump out to canvas).

Just like Figma you'd have to jump out for a lot of stuff and possibly "implement a browser inside a browser" (Figma's own words: https://www.figma.com/blog/building-a-professional-design-to...)

There's a gazillion reasons why recreating that UI in DOM is extremely difficult: browser will likely choke on that many elements, you have very little control over positioning and layout, any interactivity is likely to choke the browser due to multiple DOM updates and constant layout re-calculations etc. etc. etc.

> and I would need to have higher standards for my interface design than just "how many elements can I fit on a screen at the same time?".

No, no you wouldn't. If that was true in the general case, we would actually have actual correct beautiful performant useable useful UIs on the web. The matter of fact is that this is not the case, and web UIs are universally bad, underperforming, breaking all possible interaction modes etc.

And no. That Ableton Live UI isn't "cram as many controls as you can into UI".

> And again, I am grateful every single day that the web forces designers to think about that stuff.

This is such a bold lie.


> This is a fallacy. Not all software has to work on mobile. More over, mobile-first approach is exactly the wrong approach for a lot of software.

Okay, sure, the web would be better if it wasn't cross platform. My bad, I didn't realize that it was actually a bad thing that I can check my bank account balance from Android Firefox. /s

Come on, seriously?

I don't know if it's actually worth going through this over and over again when you are literally just re-summing up my point. That all of this, "oh interface design would be so much better" talk very often boils down to:

"I shouldn't have to worry about real-world design constraints."

I am once again, so so happy that the web doesn't give you that option. Just wait until you find out that in most industries there are literal laws around considering stuff like accessibility. In most industries you don't get to act like people saying "should blind users be able to enjoy the thing" is some kind of moral slight against your artistic integrity.

But, to very quickly go over this:

----

> 1. Complex dynamic interactive UIs are a hell for screenreaders regardless of technology. And there are no good solutions there.

As it turns out, the answer is no, these professional awesome UIs that are so great don't worry about accessibility, I was correct: https://forum.ableton.com/viewtopic.php?t=230533

And once again, the critique becomes, "but accessibility is hard when I approach UIs this way, so I just shouldn't have to think about it."

And that's why we have HTML; because software UI developers don't think about a dang thing if they're not forced to. I cannot believe someone is going to try and argue that the web is worse because it works with screen readers and adblockers and extensions and all of the amazing stuff we can do because interfaces are at their core based on text and markup.

> 2. Updating tens of thousands of elements is not an issue even for mobile. Games routinely update tens to hundreds of thousands of elements in a matter of milliseconds. If it's a problem for DOM, it's an indictment of DOM.

Games are not a shining example of flexible UIs and they shouldn't be your target for most application UIs. The reason why updating tens of thousands of elements at the same time is problematic is because signaling those updates becomes a problem for users with low vision.

Nevertheless, the web has escape hatches for this in the form of Canvas/WebGL. Of course, it's harder to use them, because they shouldn't be the default thing you reach for.

> 3. If you need to "jump out to canvas" to implement certain stuff, then you failed both your claim about screenreaders (canvas is 100% inaccessible) and your claim about "doable in DOM" (you wouldn't have to jump out to canvas).

No, if you put a canvas in front of a native slider, that is 100% accessible, there is zero issue there. People don't understand how the DOM works. You can have canvas elements in your design. The only thing that actually gets in the way of accessibility is not having the slider. But there's not a requirement that your slider be made of 40 div elements, you can use the built-in browser primitives. The screenshot you provided of Ableton doesn't have 10 thousand actual logical elements in it to update.

It's got like a couple of dozen separate controls here, maybe if you want to be real generous a couple hundred: but they're just designed using some kind of skewmorphic crud that makes them seem more complicated than they actually are. But it's literally just not a problem for a couple of grid elements in there to be canvases, I'm not saying that you have to use divs for every single element in this UI.

Of course it also wouldn't be a problem for the design of some of these controls to be simpler and more visually consistent and to use common UI paradigms instead of mimicking guitar dials, but whatever, music production is obsessed with simulating physical dials in software for whatever reason. This is why I have to run a compatibility suite to get midi plugins working between Linux and Windows, because every plugin has to be quirky and ship with an entire graphics library.

Heaven forbid that we use buttons, that would get in the way of my moral duty to make my interface look like a piano. /s

One of the reasons why working with text during interface design makes you a better designer over time is because you start to group controls more and you start to think more about controls like they're logical units rather than just as collections of pixels on the screen.

> No, no you wouldn't. If that was true in the general case, we would actually have actual correct beautiful performant useable useful UIs on the web.

People need to heck off with this. We do have good UIs on the web. Better UIs than on native in multiple cases. Your standard for what is a good UI dismisses everything that is good about web UIs, but if you actually want to talk about responsive design that works in the real world and not just for a hypothetical happy-path mouse-controlled desktop, then the web often produces better UI results than native platforms.

And the web produces this result that literally no other platform can claim even though it is far more developer-accessible than most of these other platforms that people champion. I'm so tired of pretending that because somebody laid out a UI in Photoshop and they couldn't get pixel-perfect results on the web that somehow the web has failed. It hasn't. The web gets non-programmers to produce better, more accessible UIs than these professionals on the desktop that can't be asked to give a single heck about anyone who's not a prototypical customer using a standardized setup.

> This is such a bold lie.

You're right, I'm lying I'm not actually grateful for the web, you saw through my deception! /s What are you talking about?


Where was I proven wrong? Does that example compile down to something that isn't several dozen nested divs using react?

As stated in my post, happy to be proven wrong if that is the case. I am fairly far removed from a lot of this nowadays, and it would not be the first time that the world moved on without my noticing rapidly. (My favorite example of this is just how good battery technology has gotten. A decade ago, a battery powered lawn mower was a laughable idea. )


Does it matter if it does compile down to that?

A lot of abstractions are complicated under the hood -- the high-level graphics formats that are used in engines are under the hood doing a ton of complicated tradeoffs and tricks to try and get the same sprites to render on Metal, Vulkan, OpenGL, and DirectX.

I tend to avoid over-abstraction when I can, but I still have to ask -- it a problem that those abstractions are complicated under the hood if they work for the developers that use them? Pipewire is pretty complicated under the hood to maintain compatibility with multiple setups; does that mean we can't have a universal audio interface for Linux and every device should be programming separately for ALSA and PulseAudio?


Fair that I don't think "what it compiles to" should be near as important as I was holding it.

CSS, though, did have a goal at the start to be a lot more approachable than what we have, though. User stylesheets were a huge selling point in early pitches that I recall. That is flat not possible with how we have things nowadays.

And I also think it would be fair to lay a lot of the blame on just how many divs so many designs explode things into.


I mean... I do agree with this:

> And I also think it would be fair to lay a lot of the blame on just how many divs so many designs explode things into.

That could be a longer conversation but what I try to get across to designers is that the DOM is your interface, the DOM is not the tool you use to build your interface, the DOM should be a user-facing representation of application state, and incidentally you can also represent that visually.

So agreed, I hate it when I open dev tools and I just some completely incomprehensible mountain of divs.

That being said:

> That is flat not possible with how we have things nowadays.

I do this. I maintain custom stylesheets for websites I visit, it's very possible. It's one of the things I love about the web, I love that I can have website-specific stylesheets in Firefox without even installing an addon. I've set up hacks when I was trying to use the browser less to do grayscale effects across websites I didn't want to visit. It was a tiny amount of code and it mostly just worked, and I really couldn't do something equivalent with other platforms.

And OK, sure, maybe that's just me and it's unfair for me to say it's easy. I work with CSS a lot, I am generally proficient at it. So that's maybe a bad standard for me to have -- what about the people who don't want to work with CSS a ton until they understand it?

Well... do they use uBlock Origin? There are a host of browser extensions that modify stylesheets on the fly to do complicated things that help make the web better. uBlock Origin would be a lot worse without CSS. And there's an on-ramp for that kind of thing too, HN has honestly a pretty bad user-interface as far as the DOM is concerned. But I have a number of one-line filters in uBlock that are basically just CSS rules that help make the website better.

It's not perfect and it should be better, but I'm left looking at the alternatives again -- no other platform gives me as much control over 3rd-party user interfaces as the web. And for the most part it just works, websites like Facebook are the exception and very often, particularly for indie websites, I can open up the DOM and mess with things and fix problems.

It's a problem that it's not more accessible and I am not shaming anyone who struggles with it, but I don't think it's impossible. It's a normal thing for me to do. Maybe I'm biased on that, but I think it's very feasible for especially programmers to learn to override 3rd-party interfaces on the web.

My main critique of the web is that there should be more abstractions for non-programmers and UI designers to work with that doesn't require them to drop into a programming language when overriding things. Reader Mode for Firefox is a step in the right direction, although it could be a lot better. The browser controls for font sizes are good. There's a lot further that browsers could go to improve that situation.


Totally fair that my statement is too strong there. I'm not going for a legal offensive here. :D


> Where was I proven wrong? Does that example compile down to something that isn't several dozen nested divs using react?

Why do you care about what it compiles down to? What does that have to do with anything?

As I said, your proof is here, it's just that you refuse to accept it.


As I said in the other response, I think it is fair to say I shouldn't care about what it compiles down to. That complaint is largely in pursuit of user stylesheets, where you basically do have to know the structure of the things in order to be able to adjust stuff.

I'm still skeptical, but largely on the difficulties I see frontend teams having. And despite the other poster saying they have great success with pages working on all of their devices, I daily have pages that don't. And I don't exactly visit a ton of pages. With some of these from large companies like Amazon and Google, I find it hard to believe that this is truly a solved problem. (Visiting smaller shop websites is basically guaranteed to not work on both my phone and on my monitor. Such that I don't think it is just a "big company" problem.)


Basically, at least everybody using Tailwind is doing it wrong, because they are throwing out their biggest weapon: abstraction. So that could account for the failure in the real world you see. I think there are many users of Tailwind out there.

I am also not a big fan of many of the React libraries I am seeing out there. In case of my desktop app, I am more comfortable rolling everything on my own on top of browser APIs + React.


That resonates with my view, well enough. Most of my complaint with CSS is not the idea of having a style sheet. I'd more complain at how so many people try to get the natural flow of the document to rube goldberg into the layout that they want. That and the "unrooted" nature of most styles. It can be powerful, but usually is just a mistake.


So, I'll make a concession here -- I definitely don't think CSS is perfect, and two things that are not great about it is that I'm not convinced specificity is all that good and the focus on using native elements for style names is a big trap.

When I switched to using BEM, CSS immediately became like 3x easier, especially on large projects. And there's no downside to style overrides or user customization or maintainability, there's no 3rd-party library to install, it doesn't require me to write a single line of Javascript. All I've done is change how I name classes. For users, BEM-style CSS is easier to do user overrides on through custom stylesheets than the traditional CSS that uses semantic naming.

And I do think that's a big weakness of CSS and we might have set a bunch of people up for failure by teaching everyone that the "proper" way to use CSS is to write

  main section p {
    color: red;
  }
Nah, that is asking for trouble, you will end up with soup and you will have a terrible time trying to figure out what styles are applying to what elements. Instead, use

  .Article__Paragraph {
    color: red;
  }
and all of a sudden you won't hate refactoring as much and doing style debugging in the browser will be way nicer, and when you open up your dev tools you'll see component names instead of div soup, and you'll be able to instantly grep for the code you need to change for every single style alteration you make.

Not that BEM is the only way to do that kind of thing, it's just the version I tend to evangelize most commonly. But the big thing is, use stylesheets, definitely, but don't do a bunch of nested rules that are targeting native DOM elements. We shouldn't be teaching people to do that.


Basically this is my argument for the self inflicted pain of CSS. Worse than

  main section p {...}
is when you have people start with stuff like

  p {...}
and then they start to have all sorts of woes when they realize they don't have any way to specify this particular paragraph is the one they meant. So then you end up with people being forced to use nth child selectors to hit the intro paragraph.

Then they start to think, "I want the first section to be the abstract." But should they add an "h" element to use the header to indicate a new section? Or should they make a giant container div to do the same? Why not both for different reasons throughout the same app? :D


Exactly! Zero argument on this, you are completely correct.

I do think escape hatches are important, so I'm not going to say that CSS shouldn't support referring to element types directly, that would be way too far for me to go. But...

I generally don't use direct element selectors at all when I write CSS now, and I think that teaching people to start with stuff like p {...} causes just so many problems for exactly the reason you're talking about. People are drawn to it because of that idea of everything being semantic, but styles like BEM are not any less semantic, they're arguably way more semantic because when styling you're now thinking about what an element is, not where it's positioned relative to other elements. And you get to say what an element is and what its purpose is publicly in giant capital letters in the class name that anyone can read.

Honestly, maybe I deserve a little bit more of a self-callout here because I've been kind of dismissing some of the annoyances and thinking, "this isn't that bad, you're just saying what a component should look like, yes there's concepts to learn but it's not like CSS rules are harder to learn than something like Rust" -- but part of that is me forgetting that it is significantly harder to just "say what a component should look like" when there are 5 CSS files all referring to the same elements, and so changing a rule suddenly doesn't take effect because some other CSS rule is more specific, and then changing anything suddenly breaks a completely separate part of the page over someplace else because it shared a selector.

It's like taking a function and arbitrarily splitting it across 5 different files with no rhyme or reason about which lines go where, and there's no way except by tracing the function to figure out which lines of code are ever getting called. And that's the default way that most people are taught to write CSS.

People went wild over scoped styles with web components, and to be fair scoped styles are really nice, but I never felt like they were essential for any of my projects. But if I wasn't using BEM and if I wasn't thinking about my styles as being attached to components even for completely static documents with no Javascript... yeah, scoped styles would probably be a lot more important to me :)


> For me, what they lack is evidence that stands any stronger than video games. Specifically, I've played different games on various screen sizes and orientations that largely work as you would expect. They are not perfect, of course, but they work better than most web pages seem to. And they do that, largely, without the same reliance on something like CSS that web pages need.

Video game interfaces are a ton of work, and porting between different control schemes and devices is a ton of work and that's why a lot of games don't do it. Look at the work required to handle devices like the Steam deck and the amount of work Valve has put into trying to make mouse-controlled games usable on the device. It's not easy, it's significantly more work than building for the web.

Of course it's helped by the fact that Valve does have general abstracted concepts of input that games can hook into that are shared between different controllers. Modern games don't do input per-controller, they use abstraction libraries like SDL that are designed to allow them handle a lot of different input schemes with a single codebase. And even that is a crapshoot, if you're playing indie titles on a PC you are going to be rolling the dice on whether Xbox controllers and Dualshock controllers are supported or whether only one of them works. I like that when I use the web, even weird keyboards still type into webpages. We still don't have a standardized way to do controller rebindings in games -- Valve's Steam Input works by emulating a second controller for games that aren't using Valve input APIs and pretending to press the buttons the game expects to see.

So even with all of the advantages of cross-platform frameworks, the games industry still doesn't have a great track record for building games across devices. You're pointing out that there exist games that do build separate interfaces for different devices. Sure. And agreed, when devs put in the extra work, you can have great results that are far better than the average website.

The difference is that basically every website works on my phone. Games aren't even close to that level of compatibility and most teams don't have the resources or time to put in the work to support every device and control scheme. The world of games is exactly what we don't want on the web, because if having a website interface for mobile and for desktop means that everyone needs to design and program two separate interfaces using two separate languages, we will have about the same number of websites on both mobile and desktop as we have games on both mobile and desktop -- ie, very, very few of them.

It's a blessing for compatibility that engines like Unity and Godot allow targeting multiple platforms and form-factors with a single codebase. I wish I had to work less to get that same level of abstraction in my video game interfaces.

And all of this is before we even get into all of the other problems of game interfaces -- the all-too-common lack of ability to do anything with text sizes, the lack of accessibility controls, the inability to resize windows in or out of games. My goodness do I not want my web pages to act like video games, that would be a miserable experience. It's not uncommon for me to see video games that literally won't allow changing resolutions without restarting the game. Imagine if your browser forced you to close and re-open the webpage in order to resize your window.

----

> It feels very appealing to think you can build a system that would solve "laying out text" for all time.

We have not built a system that can solve laying out text for all time. That system doesn't exist and can't be built, it is impossible. That's exactly what we're saying: we are trying to build a system that does the best possible job of universally solving that problem, but it's incredibly difficult and necessarily results in complexity and tradeoffs.

But the only belief more naive than thinking we can have one universal layout system for everything is the belief that we don't need a universal layout system and that it's possible to reduce user needs into a finite list of use-cases that can be individually supported. That reduction isn't possible, the use-cases for end users are arbitrarily large and constantly growing and it is not possible for anyone to sit down and build a single list of formats that need to be supported on the web. That's just fantasy, people are too diverse.

I use both a 1920x1080 monitor and a 3840x2160 touchscreen monitor hooked up to the same computer. Every single website I visit handles both, fluidly, when switching windows between them. A lot of games have no idea what to do and a nontrivial number of native apps struggle with it as well. But the web works, and then people show up like, "well, I shouldn't need support that." Well, I'm glad you're forced to use CSS then because I know what the web would look like if you weren't forced to.


Yes, getting an interface to work is a ton of work. If you felt that I was claiming there are easier ways that are not a lot of work, my apologies. I did not intend it that way.

My point would be more that the work Valve has put into the Deck has enabled far more than the work the standards committees have done with CSS. You can correctly argue these are solving different problems. But my assertion is that I have seen more impressive content layout and interactions from the Steam Deck than I have really with the web. I'm curious what you'd offer as the reasoning there?

You seem to be taking it that the games industry isn't very cross device focused. But, that is missing that current gen games are usually at the absolute bleeding edge of what the absolute best devices are even capable of. It is not at all surprising that those do not work cross device that well.

You are, of course, correct that there are some generic engines that allow better cross device development now than have existed in the past. Do any of them use something like CSS for laying out a menu screen? If not, why not? How about the inventory or character creation screens of games? Would you think those should be designed in the same way that something like a character builder webpage would use?

I also have large monitors, and it is ridiculously amusing how many websites do not work well when I have my windows tiling. My favorite is just two windows side by side on the main monitor, but parts of the menu of many sites will not load due to confusion over what my window width should be. To my absolute annoyance, I have found this will often not be consistent between browsers.

Now, is it fair that "bugs mean the entire thing is nonsense?" No. And I do apologize that I can see how my post read that way. Realistically, the amount of manpower that has gone into CSS has landed on something that is quite capable. But we gave up on "user stylesheets" ages ago. And the cascading nature of how things interact is almost certainly not well understood by a large portion of the practitioners. My annoyance is far less on what is capable with CSS nowadays, and much more annoyed at the rube goldberg machine that is how the vast majority of websites are layed out.


> My point would be more that the work Valve has put into the Deck has enabled far more than the work the standards committees have done with CSS.

Citation very, very much needed. Valve's work on Steam Input absolutely pales in comparison to the web. The number of supported games is minuscule. If the Steam Deck is our standard for cross-compatibility on the web, that's just really low standards. That's not the world I want to live in, CSS is better.

> But, that is missing that current gen games are usually at the absolute bleeding edge of what the absolute best devices are even capable of. It is not at all surprising that those do not work cross device that well.

No, the opposite. I'm talking about indie titles and AA titles and the average games put out by normal studios. Ironically, the giant AAA studios often have much better accessibility controls and cross-platform support. If you buy a AAA game, you're much more likely to have access to something like text scaling or dyslexic-friendly fonts or multiple input schemes, because those studios have the resources to care more about diverse use-cases, those studios have the money and developers to ask questions like "what happens if the user's TV is far away from them?"

Indie studios don't. And the fact that there's a divide between indie and AAA games on something as basic as resizing text, something that is supported on every single website -- that should be enough to show you that this "individually supported device" concept is just not workable in the real world. The games industry can't even get universal text scaling and you think that's a success story?

> But we gave up on "user stylesheets" ages ago. And the cascading nature of how things interact is almost certainly not well understood by a large portion of the practitioners

Sure, training is difficult and the web is counterintuitive to UI designers that are used to working in Photoshop, but I would still maintain that I have far fewer interface problems on the web than I do on native devices and in games, and that's not even taking into account that I see websites put up by far worse developers and far smaller teams with far smaller budgets than any of the native apps on my computer or phone.

We're never going to be perfect at this. One issue is that ironically many UI problems on the web when you dig into them often end up being due to concessions to developers on device-specific breakpoints. The web allows you to decide that you aren't going to care about being responsive and to act like you're building a video game that will only ever be displayed full-screen. If you really want to, you can design your interfaces like you're an indie developer using Unity and you can absolute position all of your divs. And there are problems with having those escape hatches, but the concessions are important because this is an unsolveable problem and sometimes devs need those escape hatches. So we add even more complexity onto an unsolveable problem to help cover use-cases that we can't cover any other way.

But solveable or not, complex or not, ignoring the problem is not the solution.

And it still is just very clearly the case to me that if we're looking at what platform does responsive design the best and which platform has the best compatibility stats between multiple devices, the web is going to win every single comparison with every other platform. It's not even close.

Yeah, things could be better, and yeah, CSS has problems, but the alternatives are just so, so much worse for actual end-users. Getting the vast majority of content on a platform to work across every single device from voice assistants to desktops to tablets to phones to VR is an achievement that no other platform can point to. And CSS does that without requiring you to have a AAA game budget when you build a website.


The number of supported games on Valve is minuscule? We clearly play different games. :) (In seriousness, sucks that you are having bad experiences there. Good luck on that changing!)

That said, you seem to be taking the strongest version of my claim here. I don't think they have solved things any more than anyone else. And I fully grant that video games are largely not accessible.

My argument would lean more into the way that photoshop and other visual tools had done things. If you want to visually layout something, using visual tools is almost certainly the correct answer. Back in the day, you would start with grid paper and literally draft out what you wanted. From there, you would have a relative coordinate system that you would then code against.

CSS and a ton of developer created things almost always focus on symbolic ideas. And it turns out jumping straight to the symbolic gets you into a ton of naming and aliasing issues ridiculously quickly. That and general purpose cascading of rules is just not that useful for the vast majority of things that we do. Is why design tools such as Figma let you put the properties directly on what you are designing. It is how people design.

And, again, I /agree/ that CSS is workable how it is today. There has been a ton of manpower put into it. But I don't know that we are comparing apples to apples in alternatives. Someone mentioned turbo pascal earlier and the form builders they had. People were doing better designs with dream weaver than I typically see online today. We didn't like it because it made the documents basically unreadable. But, we left that goal behind years ago, and missed out on the design tool that we had at hand.


> (In seriousness, sucks that you are having bad experiences there. Good luck on that changing!)

To be clear, I'm not having bad experiences on the Steam Deck, it's a fantastic device. Highly recommend it, I feel like Valve built a computer specifically for me. :) But compared to the web, it's minuscule. Compared to the web, the number of games on Steam in general is minuscule. The web is so big. Nothing that Valve is doing compares to the size and scope of what the web supports.

And in terms of support, the percentages of games that are playable across all of these devices out of the total number of games that Steam has is much lower. Again, doesn't mean that Valve isn't doing great work, but if Valve went into overdrive tomorrow and got 80% of the games on Steam working on the Steam Deck -- the web does better than that.

It would be great, I'd be very happy about it, I'd have a ton of games to play. But the web just so thoroughly outclasses that, there is no platform success story that comes close to the compatibility that the web has, and this is even with the web being a far bigger platform with a wider range of content than basically any computing platform I can think of.

It's not so much that everyone else is terrible, it's that the web is so wildly successful at getting apps to be cross-device compatible that you basically need to hit 95-99% to start comparing to it. Valve is nowhere close to hitting those kinds of numbers, even with Steam which is (as big as it is) minuscule compared to the amount of content on the web.

Valve's approach and the approach of games on Steam just wouldn't scale to the size of something as big as the web, a platform where anyone can publish anything without going through a Greenlight process or doing compatibility checks for every device.

----

> My argument would lean more into the way that photoshop and other visual tools had done things. If you want to visually layout something, using visual tools is almost certainly the correct answer. Back in the day, you would start with grid paper and literally draft out what you wanted.

Right, but I think that's just been proven to not work if you want to get a lot of people (including low-code developers and content-producers) on the scale of the web to design interfaces for multiple devices. I would argue that as inconvenient as they are, symbolic ideas are just the only way to do it.

Note that CSS allows you to do multiple interfaces depending on the device/resolution/etc... but what's important about CSS is that it doesn't allow to ignore the symbolic part, because (opinion me) the symbolic part is just part of designing interfaces.

Even forgetting about the multi-device support (which I think any platform that focuses on pure visual layout with fixed resolutions will when examined turn out to have worse multi-device support and smaller numbers of multi-device apps than the web has) -- but ignoring that, I will also argue that if you can't think symbolically about your interface and you can't lay it out as a pure-text hierarchical interface, you can't really effectively build accessible apps. One of the other reasons why I think Photoshop is kind of a bad tool for building interfaces is that I see UI developers jump into it and design interfaces based purely on "I want this to show up on this pixel" and they're not thinking about grouping, they don't have constraints to force their interfaces to be more consistent, they're not thinking about what's going to happen when the app gets translated into multiple languages, they're not thinking about screenreader support or keyboard controls.

Genuinely, I believe that forcing yourself to design interfaces in text before you sit down and look at the visuals makes you a better UI designer, because UI design cares about affordances and grouping and concepts that are being translated to the user. And without being too harsh on designers that are used to those visual tools, I can tell the difference between a designer that works in Figma and a designer that works in Photoshop because one of them will hand me a design that still works if I change the font size, and one of them will give me a blank look and not know how to react if I ask them whether we can change the font size.

I don't want to be harsh about it or put people down or be extreme, but like... I keep coming back to, I know it would be nice if we could just lay out everything visually in Photoshop. It would be great, it would make UI design so much easier. But UI design is all the difficult stuff, it's not hard to lay out things out in Photoshop, it's hard to design UIs that work in the real world. And sometimes the complaint about "why do I have to think symbolically" feels like a traffic designer saying "why do I need to worry about rush hour why doesn't everyone just drive uniformly like they do in my simulations." I'm sorry, but they don't. They do weird things and run red lights and clog intersections, and we pay UI designers to be able to handle the messy details of the real world.

> Is why design tools such as Figma let you put the properties directly on what you are designing. It is how people design.

I'll push back on this a bit; one of the strengths of Figma is that it pushes UI designers (gently, but still pushes them) in a symbolic direction. Sure, not everyone needs to sit down and write CSS by hand. Not everyone needs to learn Javascript, they can use template libraries. Not everyone needs to learn how to design websites, they can use Wordpress. There's no shame at all in building tools on top of things to make them more accessible, that's part of the web's DNA.

But Figma is CSS from the start. The CSS might not be in your face, but Figma is designed to force designers to care more about responsive design. It just has low-code options, the same as Unity of RPG Maker does for game design. But it's still thinking symbolically and logically about interfaces and not just thinking about pixels.


I don't think I ignored any points here, but in other threads we had going. I think we have a slight disagreement on how successful visual tools have been, but I see that as fine to have as a disagreement. In particular, I do not think we should force all thinking down one or the other and would expect preferences to bias people between the two. My gripe with developers is that so few seem to have ever used a visual designer nowadays.

I also realize I didn't say I enjoyed the conversation! If there is something in this one that you'd like to dive more on, please reping it.


All that said, there’s still no way to just make a layout and it be compatible with all screens. You still have to do mobile, tablet, pc modes. (And there’s enough sites that are pc-only or mobile-only.) You still have to make 2-3 layouts, but in one source. Well, what’s the argument against gp’s point again? Sorry, but this statusquoism and rationales that essentially change nothing drive me mad sometimes.


The web and CSS make it reasonably feasible to support most of those layouts well with at most 2-3 layouts in one source.

My point is that it is impossible to get the same level of results doing fully device-specific and domain-specific languages without considerably more work -- more work than would ever be undertaken by the majority of people building for the web today. If you want an indie web, if you want websites that aren't just built by corporations and professional development teams, HTML and CSS is what enables those indie websites to exist and to work across every device you own.

The proposal of using interface-specific languages and abstractions wouldn't work. Doesn't work, in fact, when you look the places where it's being attempted as a UI strategy.

Like democracy, universal design abstractions such as CSS are the worst way to design interfaces that work in the real world for real users across diverse devices and configurations -- except for every other way. If we asked devs to actually use separate domain languages for mobile devices and desktop devices, the web would be a lot smaller and a lot more limited and a lot less flexible and a lot worse for end users.


I don’t think our common ancestor in this subthread suggested separate languages for different screen sizes. Did they?


> The problem with css is almost entirely self inflicted, though. Yes, layout is hard. Why make it harder by aiming for the model we now have? Specifically, why aim for one major model that will fit all pages?

It's possible I interpreted that incorrectly? But if their problem is just making different layouts then I don't see what the issue is. CSS has breakpoints. You can already make different layouts for different screen sizes. You're not required to have one set of rules that apply to every page size.

The only criticism that makes sense to me as a reading is that they don't want a common set of UI paradigms and language features that allow targeting multiple devices and they want a more specific language targeted at describing a subset of those interfaces -- because that's what CSS is. That's the only thing that CSS is, it's just a universal rules-based language.

You can design different layouts for different page sizes, you can even on the serverside serve entirely separate HTML pages for mobile and desktop devices. The only issue I can think of left to complain about with CSS being too general is that CSS is a common language designed to be used in all of those situations instead of in only one of them.

Did they mean that they wanted CSS to have separate terminology and paradigms and ways to tackle those problems built into the language? It does! And that's exactly what people complain about, that's exactly where the "why are their 5 ways to do this" complaints come from, they come from CSS having lots of different ways to achieve the same effects based on the individual unique needs of the specific interface being created. What's the alternative, have one way of doing everything for every interface? The original commenter I was replying to said that they didn't want that.

They want multiple models for different formats, and CSS has that and lets you use them and target as many interfaces as you want, and there are ways to detect and serve different CSS and HTML based on device agents, and so... I don't know, if they don't want different languages, then what is the complaint?


I wasn't necessarily proposing separate languages. I don't see the benefit in having a single source, though. The vast majority of designs do not need to have every single element recalculated at the client.

To that end, I confess I would encourage leaning more heavily into absolute positioning of elements than most places go with. Is what I did for stuff such as https://taeric.github.io/cube-permutations-1.html, and seems to work just fine. I remember I did something similar on the job once, and the next developer came in and was against the idea of using absolute positioning. The rewrite did not go well. :(

My push is the "model" for what a page is showing should be dominated by concerns of what the page is showing. It should, ideally, not be too heavily influenced by how you want to write the styling for it. We rebelled against using tables for styling years ago. Nowadays, we shrug at the number of divs necessary.


So, I would push back against this as a design pattern, but I do want to re-emphasize, if you really want to absolute-position all of your divs, and if you want to serve even completely separate HTML for different devices -- you can.

That is a thing that CSS allows. Flexbox, responsive design -- it's all optional. There is going to be a sense when you use CSS that way that you are swimming against the grain, and that's on purpose because it's important that the instinctive default way that new designers think about the web is in those responsive terms. But even if the web pushes you in that direction a bit, it's not a requirement -- you can still design interfaces the way you're talking about, and you can heavily use breakpoints and you can have different layouts depending on the situation.

One thing that I see websites do fairly often (which I don't think is great practice but I'm throwing it out as a common practice and I understand why people do it) is literally have two versions of their menus for mobile and desktop in the same interface in the same DOM tree and just throw a "display: none" on one of them depending on the width of the screen.

So it's not even necessarily that you have to serve different HTML, you can have different versions of components even on a completely static website with no JS that swap out seamlessly depending on the user's device size.


I don't want to absolutely position all divs. But if I have one that I want to be always to the left taking up a knowable amount of space, I don't see the benefit in trying to make flow based choices so that that works out.

And fair that flexbox and such are probably fine for a lot of that, nowadays. Amusingly closer to the layout managers of early Java development days. Most of my learning was pre that. Which is why I do stress that I agree that CSS is perfectly workable.

The only real problem I see, is that sometimes the different layouts do require either slightly different markup for parenting/flex choices to work out in different layouts, or they require hilariously non-obvious markup that will work with both. Amusingly, XSLT days worked well in that aim, as you could keep the base markup only the content, but then use a stylesheet to add/remove things as necessary for display. Alas, that went nowhere.


You can just make one layout that works totally fine on all screens. Problem is you're basically just making a mobile layout and scaling it up so it'll be shit on larger screens


Heavy, heavy disagree. Tiny example, but just because it's on my mind that I need to rewrite it soon: https://danshumway.com/resume.

This is almost per-pixel identical to the resume layout that I used to have laid out in a normal editor exclusively for PDF and print, but without making a single concession with my normal print layout, it also seamlessly collapses into single columns perfectly fine on mobile devices, doesn't require Javascript, and the entire layout is ~160 lines of CSS.

And to be clear, this is bad CSS. This is not CSS I'm proud of, this is CSS I wrote ages ago that I'm going to be tackling very differently whenever I get around to rewriting the resume. But it's still perfectly reasonable to have document layouts that feel like normal print layouts that collapse down well on mobile devices.

And sure, this is a trivial example, but I think the same principles scale up. I don't believe that applications are different. Most application UIs can be represented as trees, and trees are well-suited for multiple-column layouts and collapsing rules based on width. That many sites work on mobile and don't scale up is a result of developers designing primarily for small screens and not thinking about large screens at all.

Even here, this resume should handle wider screens better, it doesn't take enough advantage of available width. But the other thing about the web compared to native is that with native toolkits if a developer designs for mobile and then doesn't think about desktop, the app just doesn't work on desktop at all and you can't use it.

On the web, if a developer designs for mobile and doesn't think about desktop, at least the interface is still usable on desktop. And vice-versa: there are desktop interfaces on the web that are miserable on mobile devices. But they work. None of the alternatives that people are proposing have that advantage.


I don't really see how this disagrees with me at all. Yeah, you can make a layout what "works" on all sizes, I said that. For something trivial it can even be great on all sizes.

But a more complex website like let's say amazon.com is much better with thought-out styling for different widths.


> is much better with thought-out styling for different widths.

When people talk about responsive design, we don't mean that you shouldn't be thinking about styling for different widths. We mean that what you come up with is a singular design that responds to changes in screen size and font size, whether that's using breakpoints, wrapping, hiding and showing elements, or a combination of all of these things -- as opposed to building a completely separate interface that the user can only access through a separate URL or application (if it's even available on their device in the first place).

Yeah, you'll get bad interfaces if you only think about one screen size, but responsive design is explicitly about not only thinking about one screen size.

Amazon is maybe a bad example here; their site doesn't implement great responsive design as far as I can tell. Scale down a window too far on Desktop and the site just throws a horizontal scrollbar at you. This is despite the fact that Amazon absolutely could collapse down into a single-column view. I disagree that Amazon's interface is so complicated that it needs a full browser width, it's a vertical list of horizontally floating elements, it's a great candidate for wrapping listings and for collapsing down the menus based on a breakpoint.

But I'm left sort of feeling like we're talking past each other. I agree that you should think about multiple sizes. I don't see what that has to do with whether or not CSS is well-suited for building interfaces, I would argue that CSS makes it easier to think about multiple screen sizes when building interfaces. I think that's CSS's strength as opposed to static layout tools that lack the expressiveness to describe what you want to happen when a column gets too narrow or to set things like margins based on text size instead of pixels or on and on. Those tools are all really useful when building interfaces that actually adapt to different settings/resolutions.


I agree that we're talking past each other. I completely agree with everything you've said here.


The world invents resizable windows in the 1980s (or perhaps 1970s).

People in the web bubble: oh it's impossible to do layout for different sizes.


Noting your comment, I couldn't resist linking to some more CSS art:

https://css-art.com/the-girl-with-a-p-e-a-r-l-css-earring/

Not sure how many centred divs are in it though...


I always found Stuart Nicholl’s CSSPlay site fun. It’s been through a lot of changes, over the years: http://www.cssplay.co.uk/

Some of the demos are jaw-dropping, if not always practical.


Thanks for that link, that is a pretty amazing demo site!


I recently spent a few days hacking flow-based layouts and pages into a flex-box-based layout system, and I can confirm that layout and formatting is hard. Figuring out how and when to shift elements to the next page, especially when you have a table with columns containing text and objects of different sizes, is a challenging exercise in picking good heuristics.


How to make sure it’s not self-imposed problem and not in-there research? In my experience, I never thought “layout hard” before joining web dev. And yes, we had scrollable resizeable windows back then. I hear that the status quo is the best way from everywhere. But then I remember my custom appkit, gtk controls and even my own (unreleased) lua-based toolkit, where centering content or wrapping and aligning elements wasn’t an effing deal, and wonder what am I missing.

And yet, that mess is really just an abundance of choices rather than constraints on what you can do

Also known as TMTOWTDI, long forgotten and buried for good.


What you wrote at the beginning is: "It is almost as if people have no idea how difficult automatic page layout and formatting is."

However, the rest of your text is: "look how difficult it is on the web, and look at all these amazing things people do despite this being so difficult on the web".

All the complexity on the web is 100% self-inflicted. It started as a simple system to display a couple of paragraphs of text accompanied by a couple of images in one rendering pass. That's it. And then it grew haphazardly, with no roadmap or plan, through a series of hacks bolted on top to give it more capabilities.

We could do the "near-impossible PhD-level stuff" in 1970s [1]. The Mother of All Demos from 1968 arguably had more capabilities than the web even today: https://www.youtube.com/watch?v=yJDv-zdhzMY

For some reason you took "it's difficult to do on the web" as an inviolable axiom of "it's difficult to do, period". The entirety of "impossible layout on the web" is about as complex as what WordStar could handle in mid-1990s

[1] This screenshot is from 1981: http://www.catb.org/~esr/writings/taouu/html/graphics/starsc... (from http://www.catb.org/~esr/writings/taouu/html/ch02s05.html)


> Nice article, the comments here are kind of amazing for a nominally technical audience. It is almost as if people have no idea how difficult automatic page layout and formatting is.

It's nuts that this is true after so many years of HTML and CSS.... software sucks any way you look at it.

Why we still can't get a bug-free OS is beyond me.


Great article. Love the interactivity. One thing that really helped me understand CSS positioning (and centering) years ago was reading about the box model. Understanding the box model helps you determine flow within the DOM. The `display` and `position` CSS properties are also fundamental to learning about positioning. MDN has great articles on these!

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

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


The "how to center" is a classic question for CSS. The fact that it is not blindingly obvious is indicative. CSS is a miasma. A kitchen sink collection of stuff designed, not by one committee, but by several committees simultaneously.

They have long since given up on actual releases. Instead, the current state of CSS is a collection of states of individual modules, all of which are under continual change.

This is not how you develop software. Or anything, really.

/rant


I both agree and disagree. This is just how how larger groups of humans work, slowly and chaotically. Herding cats. It's also not clear where we're collectively going with the web and all of its technologies, so there will be lots of failed experiments and disagreements. There's a much broader scope here than a well planned engineering project with a clear goal and path.


Regarding centering - eh. I think this question comes up so often because it is simply the natural question to ask.

What are the first things someone learning how to make a web page visually look how they want is going to learn? Probably text size, color, background color, and alignment. All of these except alignment translate pretty much 1:1 from pre-css days. Color on the body tag, size/color on the tag surrounding the text you want styled. Or, css color/font-size property on the surrounding tag, or background-color on the body. All very similar.

Prior to CSS, if you wanted content centered, you just slapped it in a <center> tag. Didn't matter if it was text or html objects like divs, tables, buttons, etc. IMO too many people expected CSS to work like what we had in the past - no distinction between inline and block objects - and when CSS didn't fit their pre-conceived mental model, these questions came up. And centering just happens to fit in the niche of being basic enough that beginners want to know about it.


According to this, most CSS issues boil down to “you don’t know CSS and have a wrong mental model”. Well, if most people who enter it have a wrong mental model, it’s not their fault that the “correct” model is absolutely alchemic in its nature.


"Software that doesn't conform to my pre-conceived mental model is poorly made".

No, what you said is not the point of what I wrote. "Wrong" in the sense that it's an imported assumption that has nothing to do with the technology at hand. And don't see anything wrong with that. Having an open mind when leaning something new is important.


Agree on the statement, disagree on the sentiment. You only have that much capacity. If people have preconceptions that clearly correspond to tasks/solutions they have in mind, it's absolutely unwise to ignore this free part in your design and design something that makes it completely irrelevant.


I love this article. Especially the interactive aspect of it. Big Kudos.

Also something I have been using since forever that almost always does the trick for me: http://howtocenterincss.com


It's taken decades for CSS to come up with anything as workable as putting content in a centered table. Yet during that same period, use of tables was shamed for layout.


HTML Tables don't wrap on mobile displays. If you build your site with tables for layout, it will probably have horizontal scrollbar(s) and you'll need to rewrite it for mobile; so a CSS framework is usually a safer choice for less layout rework, unless it's a data table.

HTML Tables need at least `<th scope="row|column">` to be accessible: https://developer.mozilla.org/en-US/docs/Learn/HTML/Tables/A...

"CSS grid layout": https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_grid_la... lists a few interactive resources for learning flexgrid:

- Firefox DevTools > INTRODUCTION TO CSS GRID LAYOUT: https://mozilladevelopers.github.io/playground/css-grid/

- CSS Grid Garden: https://cssgridgarden.com/

MDN > "Relationship of grid layout to other layout methods": https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_grid_la...

MDN: "Box alignment in grid layout": https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_grid_la...


Tables absolutely can wrap on smaller displays, that’s how we used to code responsive emails.


I can't tell if you're serious or not, but tables are an absolute mess to handle layout.

Email clients handle the CSS code to varying degree of support when wrapping responsively so even if you think your layout looks good with wrapping it's because CSS influenced the layout in whatever particular client you are using. If client doesn't support CSS or the CSS properties you've used: jank email. Email unfortunately requires you to code like 1999 in this regard.

Browsers having CSS as standard and relatively up to date is a very good thing. Tables that aren't representation of tabular data are a mess.


It's actually really simple to use tables to handle layout once you're used to it, like I said, it's what we had to do with email for a long time.

It does take some css, of course, but only width and max-width. That's basically it to turn a table responsive. Add the dir attribute and you can also control the stacking order of elements.

My point being, working in a constrained way (like with email) allows you to make the most of the properties available to you, and it turns out tables for layout (semantic issues aside) are easy to grok and work predictably and reliably.


> HTML Tables don't wrap on mobile displays

Sure they do. HN is, famously, rendered as tables.


word-wrap: break-word in one table row cell is not the same as 20% of a 240px landscape or a 1024px IE6 display.

shot-scraper supports --scale-factor, --width, --height, and --selector/-s '#elementid' with microsoft/playwright for the browser automation: https://shot-scraper.datasette.io/en/stable/screenshots.html...


> Yet during that same period, use of tables was shamed for layout.

Tables for non-table data are not semantic and break accessibility.

There is more to web development than where content lands on a page, which is only part of why good web development is hard.


Tailwind is not semantic, but no one seems to mind that for some reason.


Tailwind is anti-semantic. It's a less verbose version of the style="..." attribute. It's like people just gave up on the idea of element classes altogether.


Because they don’t work, and you end up with some pseudo-semantic but actually not hell.


Ok but then tables must be ok for layout.


I never said that they weren’t. I think the semantic purists are nuts.


And good web development is harder because still too often web design is done by designers who don't have enough understanding of web development.

My gawd, just earlier today I saw a help wanted that said "...PSD to pixel perfect..." I would have laughed if I wasn't already crying. "This is my life" and then the tears kicked in.


Haha yes I remember that.

Pros and cons of using DIVs and CSS:

+ hipster cred

- DIV soup

- CSS back then was wildly, W I L D L Y unsuitable for what people where trying to do (I think it boils down to it being designed to format documents, not web apps or on-screen layouts)

Pros of using TABLE:

+ Actually works


I never had to spend time in the old days debugging centering, I just used <center> and tables and it worked! Then I could spend the time saved by adding <font> tags everywhere and making images for my rounded corners.


I found using tables to be the most robust way at the time


Try ‘View Source’ on HN :)


No way!!!


Nostalgia. I remember those days, 2000+ lines long tables written by hand in notepad on Windows 98 and served with PWS. Those were the days.


Like many others in this thread, I think CSS is an absolute catastrophe. For me, the key issue is that style directives are constantly either 1) clobbering each other or 2) silently failing to have any effect.


I like the brutally honest cookie notice in one of the examples:

We value your privacy data.

We use cookies to enhance your browser experience by selling this data to advertisers. This is extremely valuable.


It’s interesting to note what we can learn from the use of tables for layout.

Tables have border, padding, and a cell-based layout arranged in columns. At a stretch they and their cells need white space around them, ie “margins”.

Tables are a long established element in layout.

And it turns out tables actually contain this wisdom, that all elements should work a bit like table cells: they should follow the box model (fairly obvious to anyone working in typography) but also that they should be arranged in columns (much less obvious and the foundation of grid layout and bootstrap).

It’s a natural evolution to come across some layout problems, solve them with tables (as any typesetting system is likely to support tables), and then realise that you need a new facility that has some of the properties of tables but not all of them.

CSS has discovered this. Oddly, some systems have not - for example, word processors have not unified elements under a box model etc.


Wow, all these "why is this still so hard" complaints feel so off-base to me! As the article says, Flexbox straightforwardly solves centering in every simple case. When it doesn't solve it for you, you're doing something more complex than _just_ centering, so it's inappropriate to expect that the implementation will be dead simple.


It's because for those of us who have been around a while, it was hard before flexbox, then it continued to be hard when flexbox didn't have 100% support and we kept having to track browser usage and deciding whether we could use flexbox or not, and now there are just so many ways to do it that it's an overwhelming amount of complexity. You're often not building something from scratch but rather updating old code, and having to figure out why the CSS was done in one particular way for what reason, and what might break in which edge cases, and whether you should/can update it or not, and which one of several solutions when it's not simple.

If you look through the article, none of it is intuitive. Even with flexbox, the horizontal setting is called "justify-content" while the vertical is "align-items". I personally simply can't remember what a lot of CSS properties are called anymore -- there are so many now, and the names are so arbitrary. (Even hyphens are maddening -- why is it "white-space: nowrap" instead of "whitespace: no-wrap"?)

At the end of the day, there's a big difference between:

1) Simple, intuitive, reliable building blocks that let you build complex solutions out of simple parts

2) Convoluted, partially-overlapping, constantly-needing-to-Google building blocks that let you build complex solutions out of complex sets of parts

A language like Go or Python is #1. A language like CSS is #2.


justify/align and content/items have specific meanings and the 'intuitive' naming most people expect - horizontal, vertical - completely betrays the powerful elegance of the flex model.

justify always refers to the main axis of a box model element, and align refers to the cross axis. by default, flex-direction is set to row, so justify often means horizontal and align often means vertical.

until it doesn't of course. when we switch tbe flex direction from row to column which is a very handy trick for easy responsive on small devices, the main axis is now vertical and the cross axis is now horizontal.


There's just always going to be confusion because both pairs are basically synonyms: justify and align; items and content (what's the content of a flex container? flex items).

I buy the value in having them be main-axis and cross-axis properties rather than horizontal/vertical by name, but I don't know that I buy the justify/align distinction to represent that as being meaningful or memorable.


It's very easy to remember all this, if you can just memorize the acronym AMIJAMITCOE ("Ami-Jamit-Coe"): A monad is just a monoid in the category of endofunctors.


My mnemonic for justify vs align is to picture the "justification" options in a word processor. you can justify content to the side of the primary axis when it's written right-to-left. so, justify is main axis, and the one that's not justify (align) is the one that's not main axis (cross axis).

What I don't remember ever is does flex default to row or column; so I write a lot of unnecessary `flex-direction:row;` but if you are fine with always specifying a direction, the default doesnt really matter either.


Which is even more confusing because that's not the terminology used in word processors.

Word processors have four modes of alignment -- left, center, right, and justified. Justified means stretching out to both edges.

There's no such thing as justifying content in a particular direction. And justifying something to the center is purely nonsensical.


Its similar with changing "left" and "right" to be "start" and "end" because we built in a lot of assumptions with LTR languages that don't apply to RTL.


They could leave the elegance by calling it align-x and align-y and turn-right. Or make them independent of “direction”. Or allow both ways so people could use them in corresponding situations. Instead they chose to satisfy the most useless case of a pseudo-turnable container, which makes zero sense.


For comparison, here's WPF that shipped in 2006:

   <Button HorizontalAlignment="Center" VerticalAlignment="Center"/>
(and you can write styles that apply these to groups of elements based on criteria etc)


I don't know, I constantly need to google how to work with package management in Python


Flexbox is what I always wanted CSS to be, but for a long time wasn't, until one day it was, and we could drop support for browsers without it. Feels almost end-game for CSS.

There was a reason people loved Bootstrap's grid system so much, Flexbox does all that and more straight in your browser. Cannot over-express how much I love it.


I too love flex but your comment is a bit off. bootstraps grid system is a fake grid modelled on flex. building layout grids with flex in general is definitely not endgame, its actually very tedious and unreliable.

css grid however is perfect for this and represents one of the most underutilised powerhouses in the css kit


I haven't really found much use for CSS grid. It's fine if you're doing a strict grid, but it seems to have all the limitations of a literal table to me. You can't put two objects in one cell. It has no way to wrap. It just isn't responsive at all. You can't make a sidebar with grid. You basically have to just write multiple styles and switch between them with media queries.

In practice, I find making a fake grid out of flex boxes much more usable. About the only thing grid does easier is letting you place a footer correctly. (Although you gotta make sure you count elements correctly because if you insert an extra element before your grid's footer, it will be rendered after.)


you can do everything you just mentioned with grid more reliably and by writing significantly less css than the flex method.


Grid also doesn’t break in media print. Neither does flex, but at least you can make a div of flexes, so that div breaks.


I remember when bootstraps cols were implemented using float.


Yep, there was a time when it was moderately difficult in certain cases, but it's been a solved problem for the last decade or so. You still hear people acting like centering DIVs in CSS is something like a cross between alchemy and rocket science, which is perhaps indicative that people don't follow CSS with the same attention as other parts of web development—yet they still feel comfortable making these statements!


And on top of that, flexbox has been widely supported for over a decade! The comments here are a wild ride.


This is super true. Whenever I find myself struggling w/ flexbox it helps to take a step back and solve it one step at a time. Working my way out-to-in, parent-to-child element, and it becomes so much easier. There's a skill to it, but it's basically just elastic algebra.


Having to use flexbox already feels like we're shooting a fly with an elephant gun, is the thing.

Everyone expects it to be as simple as <div centered> and everyone is surprised it isn't. That's a pretty universal experience in web development.


`<div centered>` is the same thing as `<div read-my-mind>` since there are so many variations of what you might want. And once you generalize the solution around those variations, you have something like flexbox.

For example, what does `<div centered>` do when there are two children? And what do you do when you want the opposite behavior?


> For example, what does `<div centered>` do when there are two children?

Force me to use the advanced option or to wrap the two children in a centered container? I am certain this wouldn't cover many, many edge cases, but they are called edge cases for a reason.

Edit: People can complain about tables etc being the wrong approach all they like, in the end those examples are only proof that the proper way could be at least as simple for the average case.


It takes the sum of two children’s intrinsic sizes with a margin between them and centers the bounding rectangle as if it was a single object. Flexbox does the same, and I didn’t even think of it while writing the previous sentence. But somehow you didn’t have the same read-my-mind complaint about flexbox.


Because flexbox picks a default when you give it no configuration but it lets you configure it, so it doesn't need to read my mind and it can be wrong every time.

Now show me how you change spacing/centering behavior with the proposed <div centered> and you'll finish out the point of my previous comment.


Contrast the need to use flexbox with the ability to just specify bold or italic style, or for that matter use <b> or <i> tags. You basically get what you want every time. Nobody has to argue about whether the italicization is the right slope, and while you can select a particular font weight if you want to, bold is bold and is fine for basically everybody.

Hell, I would argue that centered table contents gave people what they wanted most of the time, and if it didn't you could fix it by adding more tables. Tables composed quite nicely and gave you something if you just laid down a table and some TDs.

Flexbox doesn't scale down the way tables do. I have to have both the container and elements inside that container and think about the ramifications of all of that. It's minimum level of complexity is a higher floor than most of the HTML specification.

That's not to say it's the wrong solution for the problem; I think a case can be made that the problem itself is irreducibly complicated. But that's why I say it feels like using an elephant gun relative to much of the rest of the spec; I have a "read my mind" option for bold and italic.


Do you want your div centered vertically? horizontally? both? Relative to what? the window? the container? These are just some of the common questions that are asked every time you need to centre something. A simple attribute cannot work.


> Relative to what? the window? the container?

I don't think I ever wanted things centered relative to anything other than the direct parent, no matter what that is. I am sure some cases need it differently, but I don't see why those should prevent intuitive defaults.

> A simple attribute cannot work

Can it not work at all or just if one insists on covering 100% of cases on the internet with a single comprehensive option? I'm not an expert in this so I'm not sure, but I've seen a lot of software center items automatically and it worked quite well because they didn't assume by default that I might push the boundaries of design to new heights at any moment.


It worked exactly that way with tables, attributes align and valign:

https://www.geeksforgeeks.org/html-td-tag/


Tables only ever "worked" when compared to the poor implementation and browser support of the alternatives of its time.

In today's web landscape using tables to center categorically fails to work in many scenarios that will work with flexbox.


They worked great and still do for the vast majority of use cases.

The fact it took over two decades to surpass is not a compliment at all. Considering "internet time" (first identified in the 90s), it's a disgrace.


grid and flex were very nice semi malleable additions, they really lift the legwork and in the 10% of complex cases you can spend your brain time with joy


I've been doing webdev for a while and this is by far the best "centering a div" article I've ever seen.


Frankly, I would probably just use flexbox for any centering use case. It's simple, fast, and straightforward. As far as I understand, flexbox has a pretty well optimized implementation, so it's not really a performance concern to just throw in another flexbox. Why would you not use it?


I often don't understand what flexbox is doing when what's inside is itself complicated. I think that fits-content might help, because I haven't tried that.


https://css-tricks.com/snippets/css/a-guide-to-flexbox/

I honestly don't understand why people would find Flexbox hard to understand. Yes, there's a little bit of new terminology, and there's a reason for that. There is a main axis whose orientation can be changed, which affects the interpretation of other properties you use, but most of the time, you won't change it.


The fact that centering a div in CSS basically requires a doctorate is the entire reason I gave up on web dev.


If you think flex centering is the equivalent of "requires a doctorate" I'm not surprised you weren't cut out for web dev


Such venom.

I am sure the GP was just trying to be comedic.


Damn, that’s a harsh response


And well deserved.


So for those of us that consider this dead simple, can we just start adding CSS Ph.D on our CVs?


No, you also have to throw away 3-6 years of your life.


I don't know about that. I'm not a UI person, yet I feel like I have a pretty good grasp on CSS. I actually like it. So when I'm sick and tired of programming things, I've found myself recreating the layout of some site I liked by writing the CSS/HTML by hand. You learn pretty quick that way. It's a shame that all UI is now only allowed to be done with some library or other.


I was referring to the observation that getting a Ph.D. usually requires wasting 3-6 years of your life doing something tedious and useless (source: my time getting a Ph.D. in computer science)


Those years were called "IE 6"


was it only 6 years? felt like 20. surely it didn't qualify for early release for good behavior


My comment was partly tongue in cheek.

It did feel like 20 years, though.

According to Wikipedia, it was initially released in 2001 … which … seems later than I remember? I don't remember upgrading to it, but I guess Win 98 came with IE 5? But +20 years would be 2021 so … I guess it wasn't quite. I was using Firefox by at least 2006, maybe 2007 at the latest.


The simple version is buried halfway down the article, but:

    .container {
       display: grid;
       place-content: center;
    }
isn't so bad.


The container is body, does not need a class in the simple version.


The problem is it was easy to center things with tables. Then once CSS was popular, that was the "wrong way" to handle layout. I find CSS the worst part of web development, and it's what turned me off of front-end work. Glad flexbox has finally made things simpler again.


I like CSS but I'd agree that tables got a bad rap. They were very easy, very effective, and only occasionally turned into a nightmare of nesting that was impossible to maintain

My problem with CSS now is that it's gotten too bloated to the point where it's introducing privacy and security risks. I really want an add-on that restricts CSS by default to only a sane subset of features.


Using tables for layouts is an accessibility nightmare.


They're also awful to maintain over time, if you're needing to add new elements and require new columns or cells (and then there's the need to nest tables when using them for layout).

I attempted to fix a website by adding closing table cells that were missing, and finally got the page to validate as XHTML Strict and Transitional. The entire layout shifted, and was completely based on those missing end tags.


it's really not. It requires adding a single attribute to tables that exist for layout.


What attribute? And how do you affect the reading order? Say on a page with a side navigation?



How does that solve anything? Your dom order is still tied to your presentation.


Google for "The Web is Ruined and I Ruined It" written by the guy who first came up with the idea to use tables for layout.


There weren't really many other options in the 90's.


Not the point. The point was that some people still think there is nothing wrong with using tables for layout. The guy who started it all would like to have a word with them.


I empathize! It used to, but no longer, so give it another shot! :)


It requires single-digit minutes of work. I don't have a doctorate but I gather that it is rather more difficult.


It's about as hard as in any frontend framework, native or non native.


Did you read the article? Specifically the Flexbox example.


Maybe I missed it, but position: absolute, left: 50%, transform: translateX(-50%) is usually my go to.


Centering like this can make your element blurry on non-hidpi screens, because transforms are not snapped to the pixel grid like layout properties, and 50% can sometimes land on a subpixel


Is this still relevant? I thought browsers had proper support for sub-pixels now.


I think this was exclusive to Chrome.

https://issues.chromium.org/issues/40431598

Seems like they managed to kinda fix it in some cases, but some of the reproductions provided in the issue tracker are still working, so I would be careful


What do you do when position isn’t absolute?


Then I use one of the approaches listed. However, I find that usually I want absolute positioning when centering either horizontally or vertically.


I was kinda surprised that this method wasn't included in the article. While I use flexbox for centering most of the time, I still find myself resorting to the absolute positioning way sometimes.


Thanks for the amazing article, Josh! I‘ve come to use your CSS reset on a regular basis: https://www.joshwcomeau.com/css/custom-css-reset/


Really nice tutorial. On a related note, can somebody tell me how to make a nested div overflow (scrollbar) without specifying the height of all the parents divs?

    <div style="height: 100vh" id="one">
        <div id="two">
            <div id="three" style="overflow: auto">
                I need
            </div>
        </div>
    </div>
This is a rather simple example, but sometimes the divs are nested really deep inside and unless I specify all the childs divs as 100% height there is no scrollbar. This causes me a lot of issues.


I solved this a while ago. If memory serves me correctly, you need to set overflow none on div two. Of this doesn't work, let me know and I can check my codebase next time it's convenient.


I'm too lazy/busy to confirm/test this, but providing a new stacking context on the parent by either by adding a position: relative (or whatever) or adding transform: translateZ(0) (or X or Y) avoids the need to specify every parent's height. Someone less lazy than me could confirm :)


I'm just as lazy as you, but I just wanted to point out that you can create a new stacking context explicitly with

isolation: isolate;


oh, great tip - thanks! That's much more explicit. The other approaches have the new stacking context as almost a side effect.


I haven’t found a way to center a div with a background color containing text such that when the text wraps the overflow space (tried to expand horizontally to this size but ultimately needed to wrap) ends up being reclaimed (not background colored). Without forcing text to wrap at a certain width if it might still fit on one line.


How come the desktop UI frameworks have this issue solved for decades and CSS/Web still screwing around with mishmash of solutions? I guess, people were afraid to break stuff and kept piling garbage on top of garbage. I think it is safe to assume that the web layout systems suck.


Reasoning about the qualities of a system without having a competing party doesn’t do good in politics (dictatorship), in business (monopoly), in browsers (ie). But it’s different when it comes to layout (css).


Was the <center></center> tag really that bad after all?


<center> is a text-level element, not block layout control.


If you allowed it to control blocks, you could consider it a semantic tag with reasonable defaults.


so how do you center that vertically?

I consider it only slightly less offensive than <blink> as being useless. I also find it incorrect from attempting to have the markup dictating the layout. Sure, this was before CSS was robust, but it is one of the reasons that I just had no problem with it going the way of the dodo.


The <blink> element has never been part of any HTML standard.


your point? whether it was or wasn't has no bearing on its uselessness


I'm following on to another comment where someone uses a 20 year obsolete tag as an example of something.


and how old do you think the <center> tag is?


More than 20 years old but it doesn't matter. Use CSS and not an obsolete element.

Just checked. It was standardized in HTML 3.2. Deprecated in HTML 4 Made obsolete in HTML5


You can't modify this without touching html. Just create a div and assign class so you only modify CSS later.


What would stop it from being styled by CSS in the same way? You could use it for semantic markup.


It would be messy. If <center> element is used somewhere else then you will have to find its parent classes. If they don't have proper parent div classes or <center> used in many places then you will have to individually target <center> elements like div > div > div > center and another one div > div > div > div > center.

You can override center too but why would you try that instead of creating a class for a div and addressing it properly. Classless elements cause long-term issues when modified with CSS.


For vertical centering, I never understood why you couldn't just give the container a fixed size and then, on the element, set margin-top and margin-bottom to auto. It works like this for horizontal centering.

My guess is that the specification treats vertical margins in a weird way. For example, margin-top:50% means 50% of the width, not of the height. I don't know why they decided to do it like that.


Can somebody explain to me why centering a div is such a challenge to have an easy implementation for?

It seems like Browser makers, Languages creators, and developers all have a pretty strong incentive to solve such a fundamental, basic problem in web development to make the design experience easier.

Why haven’t these groups come together to make an easy solution to this? What am I missing?


They *have* come together. That's why we actually have several options built for purpose and native to CSS these days, as opposed to relying on hacks and Javascript (which was surprisingly common even as recently as 5-6 years ago. The name of this article is more or less a joke, because most people with any experience will recognize that since Flexbox and Grid have become widely available, the answer is generally "use Flexbox or Grid". Knowing the nuances of these layout algorithms is table stakes for building UIs that don't feel "janky".

The problem with designing and implementing application layouts for the Web is that it's such a dynamic medium. You can't ever rely on a particular viewport size, and you generally can't rely on content size either.

Like, just as a simple example: build me a page which has a white background and three blue boxes in the middle which contain white text saying "foo", "bar", and "Supercalifragilisticexpialidocious".

How big should these boxes be? Should they even be the same size? How should text wrap within them? How should the text itself be aligned within the boxes? When you say the "middle", do you mean centered vertically or horizontally? Are they laid out in a row or in a column? What's the expected behavior when the viewport size is too small to accommodate them? Should the boxes themselves wrap in some special way? Should they resize themselves?

This isn't even really splitting hairs or anything, it's just sort of the mindset you get into when you start working within a domain that's governed by *constraints* rather than specific sizes.


Because what people mean by “centring” varies depending on context. You are actually talking about a group of several different behaviours and you don’t always want the same one. So you need multiple behaviours, and you need multiple ways of specifying those behaviours.

The most obvious example: horizontal and vertical centring are different because our writing system has a specific direction it flows in. You can’t just do the same thing for horizontal as for vertical because text doesn’t work that way.


This problem was solved literally decades ago with <center>. I appreciate why that HTML tag was deprecated but I also completely sympathise with why people scoff at the complexity of doing the same thing with CSS.


<center> only centers horizontally which has been easy with CSS for years. It only gets tricky when you also want vertical centering.


this blog post and subsequent discussion is literally just about horizontal centring!

I’ve been building websites longer than most (since 1994 in fact) and centring in CSS is definitely not as easy as it was with the <center> HTML. Not even close. If it were, there wouldn’t be this entire discussion to begin with.

I swear the amount of times topics like this come up and yet a small subset of developers, likely Stockholm syndromed into believing things are great, is ridiculous. The sooner people like yourself pull your head out of your arse and realise that the current status quo is unacceptable, the sooner web standards finally mature into something that doesn’t have more footguns than the worst of C and worst of Perl combined.


> this blog post and subsequent discussion is literally just about horizontal centring!

It’s not. Did you read past the first example? It goes into vertical centring from “Centring with flexbox” onwards.


ok, half the article and most of the HN discussion is about horizontal centering. Either way, the point is still valid regardless of what percentage of the article was focused on something that should be trivially discoverable to even the casual web developer.


The <center> element is extremely limited and can’t centre things in most of the ways described by the article.


I agree. However <center> (or rather a hypothetical CSS equivalent) would still more than good enough for a considerable number of common use cases.

It's perfectly reasonable to ask a particularly language to make the easy things easy while still being powerful enough to make the hard things achievable. When it comes to CSS, or even web development in general, that isn't often the case. This discussion demonstrates that point too.

We're long overdue a redesign in my opinion.


I personally believe it was incompetence. CSS was not the first or only markup language in existence and yet here we are years later...


I was not aware that CSS was a markup language


How would you classify the language that most web pages use for specifying where to put the text and images (e.g. attempt to center it)?



If it was a markup language, it would be much easier to use. Instead, it's a rules based system that works upon a markup language (and I'm not trying to be pedantic, it would be easier if it was part of the markup, but also require much more work to change the look of content by needing to change the markup - which might be generated dynamically and difficult to change without lots of programming effort).


> Why haven’t these groups come together to make an easy solution to this?

https://xkcd.com/927/


It's all the more ridiculous because browsers can in fact center divs (block boxes), in an incredibly straightforward way, using the <center> tag. And all browsers implement this using a vendor-specific CSS rule (e.g. text-align: -moz-center). They must be able to do this, because real websites use it, and there is no other way to implement it using CSS.

And yet it's not standardized[1], so if you implement it in a new layout engine you're left with reverse-engineering what other browsers do (a classic).

[1]: OK, I lied. It is standardized... in the HTML standard. https://html.spec.whatwg.org/multipage/rendering.html#align-...

Notice how it's not a stylesheet, not a presentational hint, just prose. It's because standard CSS can't do what browsers could since before its invention.


The `<center>` element has been obsolete for 20 years and more.

https://html.spec.whatwg.org/dev/obsolete.html#non-conformin...


I mean exactly that it's not obsolete, because there is no standard CSS property that could have obsoleted it. (Even though every browser does have one; it's just vendor-prefixed.)

Ok, maybe this will make my point clearer:

    <center style="background-color: green">
    <div align=right style="width: 10ch">
    hello
    </div>
    </center>
To replicate this in standard CSS:

    <div style="background-color: red">
    <div style="text-align: center; margin: 0 auto 0; width: fit-content">
    <div style="text-align: right; width: 10ch">
    hello
    </div>
    </div>
    </div>
Or you can switch out of flow layout:

    <div style="background-color: red; display: grid; place-content: center">
    <div style="text-align: right; width: 10ch">
    hello
    </div>
    </div>
Ok, one semantic div less. But why can't I do this?

    <div style="block-align: center /* would act like text-align: -moz-center */">
    <div style="width: 10ch; block-align: right /* would act like text-align: -moz-right */">
    hello
    </div>
    </div>
If my browser understands the first variation, then getting it to understand the last one is in all likelihood not much effort; it's just substituting properties.

The only reason it doesn't, is that the property does not exist in the standard. So you have to use non-semantic centers instead of semantic divs, but that's frowned upon, so you have to use grid layout even though you aren't making a grid, just centered flow.

I just wish it were standardized, considering it's already implemented in all browsers (in the forms text-align: -moz/-webkit-center).


None of that has anything to do with the fact that the HTML standard--written and edited by all the major browser vendors--has declared the <center> element as obsolete.


Sorry, but if this is the only thing you were pointing out, then I don't see how your comment is related to mine?

<center> was marked obsolete because it's not semantic HTML, and centering stuff is the task of CSS, not HTML. It was not marked obsolete because a block-level text-align-like property would be useless.

My comment was lamenting the fact that standard CSS does not provide a compatible alternative, despite widespread implementation of the feature. Saying <center> is obsolete does not resolve this issue.


It's missing

  <div class="parent">
    <div class="child">hi</div>
  </div>

  .parent {
    display: flex;
  }
  .child {
    margin: auto;
  }


+1

Very well done!

Clean and to the point - virtual coffee on me!

As someone who jumps on-and-off of webdev it can be a little frustrating catching up on latest javascript frameworks and, at lower level, modern Javascript and CSS.


The demo containers and their animation are so cool and useful.


The article is great.

His avatar popping up mid scroll did “startle” me, though. A bit creepy sneaking in slowly from the edge. But it's effective, for sure.


As far as “subscribe to the newsletter” prompts go, that wasn’t as annoying as what I usually see. Still, would prefer it to have been on the right side so it didn’t obscure content.


<table align=“center”><tr><td><div>Here you go!</div></td></tr></table>


I prefer the simpler:

  <center>Here you go!</center>


Classic!


After over 10 years since I started using CSS, nothing changed. Center div still hard.


You have passed Level 1.

Level 2: Put a form and form elements in it.

Level 3: Do it with flex.


for the uninitiated:

<div style="display:flex;justify-items:center;align-items:center">

    <div>I'm centered</div>
</div>


That doesn't work on Codepen.io, in the latest Chrome.

Back to the drawing board.


<div style="display:flex;justify-content:center;align-items:center;">

    <div>I'm centered</div>
</div>

* I wrote the original without testing but it is justify-content, not justify-items... oops



Nice intro. I always feel like I'm fighting css.


Always learning something new from Josh W Comeau


Great article but why would I need a div?


Every. Time. Man.

I love his posts. So much information and insight. But why the hell does a guy obviously so good at UX stuff fuck around with my scrolling? I cannot stand it.


I was about to yell "Another basic CSS guide" but I was proven wrong. Every annoying centering issue is addressed in detail. Very well written.


Can't count how many times I've searched centering in divs over the years.


in css, things seem easy in isolation.

it's when you combine styles and inheritance that things get nasty.

then add on top:

viewports,

orientations,

layouts,

negative margins,

collapsing margins,

relative positionings

...which can make even "simple" centering into a 6-dimensional puzzle.


TLDR:

place-items: center;


Tldr - it's impossible


[flagged]


> Oh, no, please, not another "centering content using CSS is really, really simple: it's just you that is dumb" think-piece...

That doesn’t resemble the article in the slightest.


The lead-in to said article:

"For a long time, centering an element within its parent was a surprisingly tricky thing to do. As CSS has evolved, we've been granted more and more tools we can use to solve this problem."

...yeah, but still none of these tools like, actually work?


>but still none of these tools like, actually work?

But they do?


Where does that call people dumb?

Everything in the article (apart from “Centering in the future”, obviously) works.


It sounds like you didn't even read the article, the contents are nothing like what you describe.


What about "[...] centering an element within its parent was a surprisingly tricky thing to do. [now...] more tools we can use to solve this", and the subsequent complete lack of a list of these tools that work cross-browser did I miss?


Flexbox has been stable across all common browsers since 2014 or 2015 or so, depending on how you draw the line.


Flexbox is in every browser.


This guy's page never pops up in google search... My only problem is, that sidekick on the page is quite irritating. Can't we have some kind of furry fantasy creature instead?




Consider applying for YC's W25 batch! Applications are open till Nov 12.

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

Search: