Hacker News new | past | comments | ask | show | jobs | submit login
Centering in CSS (web.dev)
335 points by feross 69 days ago | hide | past | favorite | 160 comments



I get TIMTOWYTDI, that it's good to have more than one way, but each seems equally inscrutable. Can you imagine explaining any of these to a novice who just wants that box to be centered and stay centered? When they ask "Why is there no simple 'alignment:center' option for the named thing?", what can we say other than "but look at all this jargon with the word 'center' in it! Easy! Now go back to your selectors!"

CSS always feels like less of a languages and more like a bunch of hacks crammed into the browser. And the inscrutibility leads to copy-pasta code: search for a sample, paste it, it works now, mostly... But when it breaks, newbie dev will struggle to untangle. (Ruefully, speaking from experience).

I know, many folks love css, but I find it a big mental discontinuity from html and js. It's solving a different problem, sure, but I look forward to some future version of styling which might offer a more "readable" experience.


I sympathize. Been doing webdev since 1998 (before CSS). Most CSS in the wild is just awful and virtually unmaintainable. I can't recommend highly enough that you and everyone else (the overwhelming majority) who feels the same way head to https://every-layout.dev to learn about "Axiomatic CSS". It explains and illustrates not just layout but virtually everything you need to know about leveraging standard CSS, building up from clearly-articulated and unimpeachable first principles. The axioms and examples on the free site are profoundly useful, and the $100 book / full site / component generator are more than worth it.

Disclaimer: No affiliation, just a grateful customer hoping these ideas catch on.


thanks - you've just sorted my Christmas project for me. I've tried to wrap my head around CSS layout several times. On each occasion, I've come away with a perplexed sense of "but.... surely it shouldn't be as hard as this?". Layout is about the relationship among elements. CSS - as far as I could see - is based on styling elements within containers. There's little or no ability to express peer-to-peer relationships directly.

First example on every-layout and already I have a fresh perspective. For example, under stack [0]:

"margin is really a property of the relationship between two proximate elements. "

and then a solution for styling the relationship directly.

[0]: https://every-layout.dev/layouts/stack/


Thanks for posting this. As someone new to professional web development, stuff like this is a valuable resource.


It's designed around the idea that the user chooses the width of their browser and the page becomes as long as necessary to fit all that content by scrolling, just like a word document. Centering, especially vertical centering, is kind of hard to define in that context.

When you start adding features to give web developers pixel-perfect control of the viewport then you impede other features like allowing the user to choose their own font sizes while still having everything render in a sensible way.


Apples AutoLayout already does this — and in a much more elegant way. I’ve been making MacCatalyst apps recently and have been searching hide and wide for a 1:1 UIKit/AutoLayout <> Web front end (aka a rats nest of js, css and html).


I would argue AutoLayout has a way easier job: There are less backward-compatibility concerns, everyone is using the same GUI-based editor and there are many less device configurations to account for. It is also arguably less flexible than the Web in terms of the range of UIs that you could create.


*searching high and wide :)


Grazie — Sent from my iPhone and != proofread ;)


It's designed around two ideas:

1. A page is tet + images. Complex layouts are very late invention for HTML

2. The whole layout can be done in a single pass.

This was crucial for the 90-s era browsers because you wanted to be fast on rather underpowered machines. I think double-pass was permitted/mentioned in standards only around 2000/2001 with relation to tables (I forget what it was exactly). Centering an element vertically may require several passes (do the rest of the layout, layout the component, layout the component centrally, possibly reflow the rest of the document, etc.), and it was a big no-no


I try to explain to my junior devs why a 3-column layout was considered the "holy grail" at the time. Why we needed Firebug. SWFObject. Why I can type -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=50)" from memory. It was ridiculous!

The last centering example (left with translate) was fun to explain to junior devs too.


Can you imagine explaining any of these to a novice who just wants that box to be centered and stay centered?

Layout is a hard thing that looks easy until you get in to the details. This is no different to talking to a junior C developer about transferring data and them asking why there isn't just a single simple and robust way to send structured data from one server to another. We have JSON and Unix sockets so why do Protobufs need to be a thing. Because their lack of experience doesn't give them the depth of knowledge to understand why it's actually hard, that's why.


> TIMTOWYTDI

what?


> There's more than one way to do it (TMTOWTDI or TIMTOWTDI, pronounced Tim Toady) is a Perl programming motto.

https://en.wikipedia.org/wiki/There%27s_more_than_one_way_to...


Why am I not surprised that this unreadable mess of an acronym is a Perl motto?


Sorry, showing my age and inability to spell and lack of appreciation of the pain of inscrutable acronyms... in a post about inscrutable languages. Ouch on me.


there is more than one way to do it


I know, many folks love css, but I find it a big mental discontinuity from html and js. It's solving a different problem

This is actually the misconception that leads to confusion with (and ultimately, poorly written) CSS.

It comes from a misunderstanding of what creating a web page actually is.

As Alan Kay once remarked, “A change of perspective is worth 80 IQ points.”

This is no less true with CSS.

Most developers view CSS an annoying 'styling' language, that's 'not really a programming language'. Which separates it in your mind from the engineering frame of view that tends to excite you as a developer.

This makes CSS tedious to use.

In truth, HTML and CSS are parts of a holistic language of layout construction. They work in unison, not as individual components. Very much an engineering toolset. Just that the problems to be solved are more visual in nature than you're probably used to.

Instead of seeing CSS as an annoying way to 'style' pages, see it instead as a visual programming language for constructing visual guides (UI's) for your user.

You don't 'style' pages, you 'construct' and 'architect' them. It sounds weird to use these words, but they have a massive effect in changing your perception of what you're doing. And that has a massive effect on your impression and willingness to learn how to do it well.

I think that understanding this is one of the key differentiators between developers who are good with CSS and those that struggle.

Tools like TailwindCSS (that lead to a massive increase in both productivity with CSS as well layout maintanability) are based on this fundamental premise.

I expand on this more in a recent post called "How To Get Better At CSS", which you can read here: https://planflow.dev/blog/how-to-get-better-at-css

Sidenote: I'm also working on a book that aims to help you gain mastery over CSS, showing you how to truly understand it, by learning how to debug its most common issues as well as re-framing how you see it in the way I've described above. You can check that out here: https://gumroad.com/l/Debbg/z823cp8.


> Instead of seeing CSS as an annoying way to 'style' pages, see it instead as a visual programming language for constructing visual guides (UI's) for your user.

> You don't 'style' pages, you 'construct' and 'architect' them. It sounds weird to use these words, but they have a massive effect in changing your perception of what you're doing. And that has a massive effect on your impression and willingness to learn how to do it well.

I honestly don't understand what this means (I read the corresponding blog post but am still confused, unfortunately). Could you expand, possibly?


Have you ever found that your enthusiasm towards something changed once somebody explained it to you from a different perspective?

A lot of the problem developers have with CSS, has to do with the way they see it.

Developers don't typically like to 'design' things in the artsy sort of way. But they do like to engineer them. CSS can be viewed from both of these perspectives very accurately.

The latter however, generates more enthusiasm for the developer. And enthusiasm is key to everything else.


Yeah I mean, sure you 'construct' and 'architect' the web page but you definitely still 'style' it and using different words doesn't make CSS any less annoying to use


Semantics do actually matter quite a bit. They are what ultimately determine your frame of reference, and ultimately, how you use a thing.

It's more of a mental model with which to see it. If you view a webpage as something to be 'architected', rather than as simply something to be 'styled', every else you do (as well as how you feel when you're doing it) changes.


I am happy that you think that works for you but I have a hard time believing that it will have any actual meaningful effect for most people. You can describe an activity in any different set of synonyms but the activity at its core does not change.

Your approach reminds me of a cross between "neurolinguistic programming" and the character Tom Sawyer when he convinces everyone that painting a fence is fun.


> As the late great Alan Kay once remarked

Alan Kay is still alive.


I had been referencing someone else with another quote initially, forgot to remove that part. My mistake! Have now edited to fix.


> You don't 'style' pages, you 'construct' and 'architect' them.

> I think that understanding this is one of the key differentiators between developers who are good with CSS and those that struggle.

Yeah, no.

HTML is a single-root hierarchy whose only primary job is to display text and maybe some images. That's it and it pretty much sucks even at this job.

CSS is and will remain a bunch of hacks trying to force the web page into something it's not. Saying that CSS and HTML are meant to be used together to construct and architect pages is some serious re-writing of history and evolution of CSS and some impressive mental gymnastics.

For a great immediate overview why that is, it's enough to look at this page: https://csstriggers.com When changing text-shadow causes your entire page to reflow and repaint, there's no "architecting" or "constructing". It's piling hacks on top of each other in the hopes it somehow works.

For most of its life since inception in 1996 CSS was nothing but simple styling of HTML pages. There were a few feeble attempts like `display:float` and `position:absolute` to pretend it's not, but the enduring resilience of the Holy Grail kept obliterating that idea. This changed around 2008 with the meteoritic rise of mobile phones and mobile apps (thanks, Apple and Google). It still took w3c 5 years to come up with a solution that could barely place boxes in a relative position to each other without increasing developer suicide rates. I'm talking about flexbox, of course.

Side note: Terrainformatica's Sciter had already had a solution to this for several years, and it was simpler, faster, and required significantly less cognitive load: [1] Not to mention Cassowary which was proposed all the way back in 1999 (can't find the link now).

I think it took MS and then w3c a combined of 10 years to get Grid off the ground.

And all that to be able to finally say: hey, we can barely position an element vertically. Of course, they still can't, as the OP link demonstrates: you need a brand new layout module + a brand new alignment directive to achieve something most GUI libraries in the world have had since Palo Alto's Xerox in 1979. And yeah, it still has cons that has to be remedied by "Gentle Flex".

And, of course, all of this is as brittle as the tail of Prince Rupert's drop. You even glance at it sideways, and it breaks in countless unimaginable ways. Attempt a slightly different layout? Just lift the layout with the markup and attempt to place it in a different position on the page? Adjust sizes in the most minuscule way? Place these things side-by-side? Oh, great constructing and architecting work guys, everything is broken.

And, of course, it cannot be in any way, shape or form properly refactored because it's a flat system where everything is global, styling a single tree tailored to display text and images.

[1] https://terrainformatica.com/w3/flex-layout/flex-vs-flexbox.... and https://terrainformatica.com/2018/12/11/10-years-of-flexboxi...

From last link:

--- start quote ---

As a result 12 (sic!) new flexbox-only-properties were added to already huge CSS property namespace (200 properties and counting). All that just to make FlexBox anyhow useful.

But the biggest problem of the solution is that the flexbox breaks existing CSS box model – dimensions of elements are now defined not just by width/height properties but bunch of others like align-items and align-self.

Go figure out why “align” property shall change dimensions and why explicit height:100px declaration shall be ignored

--- end quote ---


Languages (and technologies in general) evolve. And as they do, it's helpful to evolve your perspective towards them alongside it.

Mobile phones started off as simply ways to call people. Are they not much more than that now? Would approaching them with only their original perspective be as helpful today?

No. The perspective has completely changed. Now, the more accurate one would be to approach them as full-blown computers.

> HTML is a single-root hierarchy whose only primary job is to display text and maybe some images. That's it and it pretty much sucks even at this job.

While HTML and CSS started in the ways that you've described. That's not what they are for now.

> Saying that CSS and HTML are meant to be used together to construct and architect pages is some serious re-writing of history and evolution of CSS and some impressive mental gymnastics.

I'm not rewriting history. I'm re-framing the CURRENT perspective of these technologies, in a way that is much more helpful. What use does framing HTML and CSS from the perspective of their origins have?

How does this help you create with it today?

With modern considerations that are more in the realm of architectural thinking than they were before?


> While HTML and CSS started in the ways that you've described. That's not what they are for now.

Has HTML eveolvd beyond a single tree? No. Has HTML evolved beyond displaying (barely) just text and images? Also, no [1]. Have HTML and CSS evolved to a point where it doesn't involve a reflow/repaint of the entire page or large chunks of a page to do the simplest things? Also, no. Have there been significant updates to the DOM model? No.

> What use does framing HTML and CSS from the perspective of their origins have?

It helps you understand what the are, not what people pretend they are. It also helps you understand why things are they way they are, why so many things are complex, or impossible, or interact in unintuitive ways with each other, or why a 10-page essay on how to center an element ends up with a yet another "gentle flex" hack reminiscent of the "Search for the Holy Grail Layout" of 10 years ago.

Because no matter how many times you use "holistic" and "unison" in your speeches, it doesn't change what HTML + CSS are essentially are at their very core that permeates everything: a way to display (rather poorly) static content that consists of text and a few images, in as few render passes as possible (because it was developed for the 90s era computers). Everything else is a series of gargantuan efforts costing millions of dollars to try and mold them into something they are not.

[1] There is a reason why most UI frameworks for the web (doesn't matter whether it's pure CSS or it's Javascript through and through) implement the same half-a-dozen to a dozen components: a button, a label, a badge, breadcrumbs, a text input. Very few dare to implement a date picker. Even fewer go for complex elements (actually working accessible modal dialogs, virtual lists, tree views etc.). Because the moment you step outside the "text + images" capabilities of HTML, you're screwed. And no amount of hacks added to CSS can help you with that. I won't even mention the impossibility of high-performance animations. Sure, you can CSS-transform something... as long as the original element stays in place and never moves because actually doing proper stuff in "CSS and HTML that's not the same now" is just as expensive and nearly impossible as it ever was [1.1]

[1.1] https://css-tricks.com/using-css-transitions-auto-dimensions...


Hands up for anyone else who remembers how much worse this was in the CSS 2.1 days when it had to be hacked using `display: inline-block` and tricks involving negative margins.


Absolutely. I remember how it was to make your website work in IE6 and later in IE7's Frankenstein compatibility mode.

All those dirty hacks you needed to do to make stuff work make me so thankful for today's wonderful CSS, even when it frustrates me.


After fighting years against IE6¹, when IE7 came bantering in with its Compatibilty Mode, I gave up and moved to backend work. Spending weekend-allnighters to get this one rounded-corner-drop-shadow working is depressing.

¹ a real-life lesson in monopolism: IE6 was around for over 14 years!


Stuff like 99% support flexbox and high % for grid makes working with layout so good.

Only wish "gap" property would be adopted easier to make working collapsing flex rows way easier.

Even the basic things like :last-child selector is good quality-of-life improvement.


inline-block was cheating. Plus, for a long time after it was "released" you couldn't rely on browsers actually implementing it. I always used `margin: 0 auto` and if you know the height of an element, you can set the top to be 50%, and use a negative margin half its height.


I'm really hazy going back this far, but wasn't it that it worked in Firefox and Opera, but then IE could be handled using magic HTML comments that served it special separate rules? I know sometimes IE's vendor-specific CSS "expressions" system could be used to compute properties like max-width and so-on that it didn't otherwise support, and it was nice to be able to do that without requiring a JS polyfill.


There were conditional comments for loading IE specific things. And I remember IE6 having .htc files (html components), csspie is the one I remember


Reminds me of having to use (CSS) floats to position stuff. CSS grid and flexbox have made positioning (in particular, vertical positioning) so easy.


Floats and clearfixes everywhere


The horror:

*:after { visibility: hidden; display: block; font-size: 0; content: " "; clear: both; height: 0; }


I still remember using `display: table` and `display: table-cell` for getting vertical alignment as well.


I remember wrapping entire content blocks in table markup to center them :(


Reading articles like this, my basic impression is that, after CSS has been around for twenty years or more, it’s still complex to do simple things that everybody wants.

Is this why the web is less successful than it might be?


> it’s still complex to do simple things that everybody wants.

People underestimate the complexity of layout. Take vertical centring, for example. The immediate assumption is that it’s easy; you just find the mid-way point between the top and bottom. But the top and bottom of what? The web is a document-based system, with text flowing from top to bottom. The centre in this context is not the centre of the window, but the centre of the document.

Okay, so let’s find the mid-way point between the top and the bottom of the document. The top is easy, it’s zero. So where’s the bottom? Well to find that, you need to know how tall the document is. How do we do that? Well, the height of the document is defined by the height of all of its contents. So let’s render its contents and find the height. But wait – the thing we are trying to render in the centre is part of the contents, so we’ve got ourselves into an infinite loop.

There are various solutions to this – hard-code the height of the document (to what?); take the thing being centred out of consideration when rendering the rest of the document (and now it can’t affect / be affected by the rest of the contents), etc. But which solution is best depends upon the context – and this is how you end up with complexity. It’s easy to say “just put it in the centre”, but it’s not as easy to figure out what that means exactly or which solution is best for doing so.

> Is this why the web is less successful than it might be?

The web is one of the most successful technologies in the history of human civilisation. It seems quite odd to talk about it as if it were a flop because you have to think for a moment before centring something.


Yep, GUIs are always hard.

I don't know what it is about the web, maybe because it's so accessible, that makes people assume its GUI abstraction should be easy. Or that because web GUI is hard then the web's abstractions are basically a failed experiment. Or, HN's favorite, that we're somehow trying to build things with these completely anodyne GUI tools that they're somehow not meant for.

But it's hard because GUIs are always hard. And the things that make HTML/CSS hard are the threads that run through all other GUI abstractions and make them hard.

Notice how Android and iOS developers are never piling into HN circlejerks raving about how Google and Apple have really solved GUIs.

Here are six different ways to center a square in a box in UIKit with constraints: https://stackoverflow.com/a/26181982/511200 I've been an iOS developer for over five years and I still consult this regularly when checking constraint spaghetti to make sure it's not missing any bits of the magic incantations.


Layout for GUIs are hard.

And HTML nor CSS weren't developed with layout in mind. The original idea was to mark up (the M in HTML) meaning and semantics and leave the rendering and display to the client entirely.

If you consider that systems that were designed entirely around layout (Like QT layout https://doc.qt.io/qt-5/layout.html), are complex and hard, you can imagine what happens when you try to do layout with a system that was never intended to handle this, must be backwards compatible, is a standard (not a lib or framework) and can be freely interpreted by renderers by definition.


I guess this supports my point. It's a hard - and necessary - problem to address, and HTML and CSS are not very good fits for it.


I much prefer doing MacOS or iOS layout work rather than working with the absolute clusterfuck that is HTML and CSS.


I vastly prefer web client development where there are much better abstractions and I have rather arbitrary freedom.

I think web GUI tools are simply better and I think my StackOverflow is one example why. The web also has a full spectrum responsive solution.

Even Apple is transitioning from 90s KVO tech to SwiftUI, a buggy experiment that looks like any of the reactive/observable weekend frameworks that the web has been experimenting with for 10 years.

One thing I notice is how little cross-experience there is. The iOS developers I work with have barely built a web client, and web developers have barely built a mobile client. I bet 95% of our opinions including my own are driven by familiarity, and we just like to roleplay that it's some deeper technical calculation.

That said, even if the iOS dev experience was 10x as good as it is today, I still wouldn't pick it for personal projects because polishing an application that only iOS users can use is a nonstarter. That downside got old so fast.


Let me guess, you did not do any iOS development? To claim that web has better abstractions is insanity. Even before autolayout to say that was a stretch.

And I say this because I do have that cross-experience: working with web since 1998 (1996 non-professionally) and with iOS since 2010 (professionally since 2012).


> The web is a document-based system, with text flowing from top to bottom.

This was always the central mistake in the design of CSS. It was solving a problem people just didn't really have. I mean, yes, it did both simplify and improve the situation for this sort of document flow kind of thing but we were all using tables for a reason:

Because what people needed was a mechanism to describe structured layout. Inside that, document flow is important, but we spent 20+ years just getting back to the structural power of tables and it's fucking ridiculous.

And it did it all in a way that required the exact constraint solving complexity you're lamenting. But it didn't really have to be that way.

CSS was a disaster and has almost certainly wasted incredible amounts of time and money that could have been better spent if a better solution had come along in time.


> we spent 20+ years just getting back to the structural power of tables

Already CSS 2.0 (which is indeed 20 years old) had the power of tables through the "display:table" property. Flexbox and grid gives you additional power.


You could also just keep using <table> tags. Either way, they interact strangely with other aspects of CSS and you have to structure your "document" in a very particular (very likely non-semantic) way in order to use it for layout.

Having an escape hatch to break the box model completely so you can do useful things with it is not actually giving you any structural power, it's just admitting the weakness in the model.

Fundamentally, what was always needed -- and what flexbox and grid finally started bringing -- was the recognition that structural layout and semantic structure are rarely the same thing, and that you need to be able to describe them separately, usually in separate hierarchies.

Still, they do it in a fairly convoluted way that only really feels simple by comparison to what came before.


> Having an escape hatch to break the box model completely so you can do useful things with it is not actually giving you any structural power, it's just admitting the weakness in the model.

I don't really get what you are saying here. Are you saying display:table or display:grid breaks the box model? Because I don't agree with that interpretation. But maybe I misunderstand.


display:table and display:grid are not really the same class of thing? One lets you make things act more like pre-css html, the other is a completely new addition to the box model.

"breaks the box model" might be too strong, I'll admit. But table-styled elements don't act quite like other things in the box model even so. It's confusing and messy and anyways you have to contort your document to fit things together in a way that works with it most of the time.

On the other hand I'm saying display:grid is good, but took way too long to get here.


I don't see what is confusing or messy about display:table. Of course if you use it for a purpose it is not suited for, it gets messy. But so it is with everything.


   > You could also just keep using <table> tags.
No. This often repeated and it is always wrong. I just won't bother anymore to tell why it is wrong, there is no point talking to people who will not listen.


> not as easy to figure out what that means exactly

I wholeheartedly disagree. When you see the title "centering in CSS" you know exactly what it means. It's the same old problem everyone has been solving repeatedly for 20 years. It's not about edge cases. It's not about exceptions to rules self imposed by your specific needs. It's just centering inside a box. And the author of the article knows this, and solves it again for us for the nth time with updated techniques.

The issue isn't how complicated a layout is or needs to be. If you were to look at how horizontal center is implemented under the hood, it's going to be complicated, yet that complexity is abstracted away.

It boils down to the simple fact that intuitively when we've had <center> forever, why couldn't there have been a <vcenter> from the beginning? Not even broken, it never existed. It's as if we're being told, "horizontal centering we'll handle, but vertical centering is for you to figure out". Err, why? And figure out based on the tags and attributes provided. Like, they implemented the puzzle but not the solution.

Similarly, why can't "vertical-align: center" just work more often? The fact that a div needs to be a table-cell or a grid, or having the option of using <td> that still works should all be redundant. There is nothing ambiguous about wanting to vertically center.

We're always reverse engineering from a need. Complex needs justify complex code. Simple needs should be simple declarations.


> why couldn't there have been a <vcenter> from the beginning?

Because HTML is incrementally rendered. The content of <center> can be rendered line by line as data arrives, but a <vcenter> would need the full content to be loaded before it could be rendered, since you need to know the dimensions of the content before you can center it vertically in a container.

Vertical centering cannot be supported in the ordinary top-down incremental flow rendering. It requires a more complex layout model like table, flex or grid.


I'm sorry but this is nonsense.

When you have an img tag in an html document, and that image takes a while to load and has no pre-set width and height, guess what: the document renders fine and everything else adjusts when the image is finally loaded and its size is known. There's really no reason at all that a <vcenter>ed element couldn't be vertically centered at all times within its containing box, even as its containing box changes size, except a stubborn and dogmatic unwillingness to accept that web pages aren't magazine layouts.

It would be more accurate to say that HTML is progressively rendered. As information comes in, boxes move and change size and eventually settle in their positions.


> everything else adjusts when the image is finally loaded and its size is known

Yes, this is called reflow. At the time <center> was introduced, browsers did not support dynamic reflow (except by re-rendering the whole document from the top). For example tables had to be fully loaded before they would be rendered, and the same would be the case for a hypothetical <vcenter> element.

<center> on the other hand can be progressively rendered without requiring reflow.

My point is just that vertical centering requires a more complex layout model than horizontal centering.


And my point is regardless of how complex something is, unless it's impossible, you can just give the thing a name and hide the complexity under the hood.

Imagine if this just worked since html1:

<div center vcenter>centered</div>

And this since css1:

<div style="align:center; vertical-align: center">centered</div>

Why are we still talking about how to vertical align elements in 2020? That's the question. Having to discuss history as an excuse to why anything is, is a symptom of the problem.


> At the time <center> was introduced...

... CSS didn't even exist yet.

I don't think anyone is suggesting that vcenter or something like it should have existed at that time. The point is that it could have certainly been introduced by the time css came around and started handling more than basic text styling. It's been over two decades since that condition held.

The "more complex layout model" has been here a long time.


> ... CSS didn't even exist yet.

> I don't think anyone is suggesting that vcenter or something like it should have existed at that time.

Uh, this subthread started with exactly that question:

> It boils down to the simple fact that intuitively when we've had <center> forever, why couldn't there have been a <vcenter> from the beginning? Not even broken, it never existed. It's as if we're being told, "horizontal centering we'll handle, but vertical centering is for you to figure out". Err, why? And figure out based on the tags and attributes provided. Like, they implemented the puzzle but not the solution.


I mean, sure, I guess you could take it as literally as "in tim berners lee's original browser version" but frankly, CSS and the ability to reflow the document is so old at this point that getting anal about it not being literally there since the beginning of the web is just silly.

Have perhaps a little bit of charity and assume that what was meant there was "since it was possible".


I mean, all the comments I got were not about my main points at all.

"No you should do this because of that" is not a valid argument when both "this" and "that" only exist because you created them. If vcenter was part of the original spec, we would have it because the browser publishers would have made sure they fulfilled the specs. We have yet to have it. We are being told valign is a complex feature, and we just accept it.

But you should always model your specs based on use case, because that's who you're serving. Anything less than that is ego and dogma driven development.

And to me, the most disappointing and damning evidence was that w3c does not even author their own web site. They are not users.

https://news.ycombinator.com/item?id=24596769

Being from MIT, I could only imagine how fun a student driven implementation effort could be, and they'd do it for free. I was not alone in 1999 building web pages in an Athena cluster.

Not sure why writing on HN is so often a negative experience. Not sure why I keep doing it.


Have you considered proposing your idea to the CSS working group? The w3c are just the editors, CSS is developed in the open and anyone can propose extensions.


> It requires a more complex layout

Yes and no.

Yes, because vertical centering can be implemented manually using these available elements as you said.

But no, because all it takes is one of these solutions and naming it "vcenter" under the hood and not having to interact with any of it. And that's exactly what we do using classes or using a css framework that provides for better abstraction than vanilla css. And as the original article demonstrates, there usually is one best practice that checks all the boxes.

It's not that vertical aligning is buggy or that it doesn't work or that it's not possible. There was never a tag for it as if the need wasn't acknowledged, even with the browsers fully capable of doing it as demonstrated by every webmaster that did it since css1.

And to add, complexity is never a reason when you're capable of abstraction. The main issue with CSS and HTML is there is no "let". You're always forced to deal with the specific tags directly. Instead, javascript is provided as a tool for abstraction. So again, it's all possible. We just have to do it ourselves as opposed to there just being a "let".


> why couldn't there have been a <vcenter> from the beginning?

So if you want to support a layout that adapts to the size of a viewport you'd do what? Go through DOM with JS on each size change and rewrite DOM from <vcenter> to <somethingelse> and back?

With CSS as is, it's fairly easy to achieve.


Vertical centering would work just as horizontal centering works in 99% of the cases as expected. The syntax could be symmetric. We override and adjust as needed. Instead, we have nothing to override or adjust. We're forced to pick a layout system just for a specific feature, and add 5 lines of code that now interferes with everything else.

The argument isn't that it's hard. It's that it could be so much easier. But also, that there just might be a fundamental issue with the philosophy of what could have been just html has evolved into the monstrosity that is css/html/javascript+framework+backend_render... with "the inability for vertical alignment to declared simply" as evidence.


I'd like to be able to say:

    .child-element-selector {
        centered-inside: .parent-element-selector;
    }
And let the browser figure out what I mean, taking into account border widths and parent element padding, for example.


> Well, the height of the document is defined by the height of all of its contents. So let’s render its contents and find the height. But wait – the thing we are trying to render in the centre is part of the contents, so we’ve got ourselves into an infinite loop.

What? Where did the loop come into it? The height of the document is defined by the height of its contents. The thing we're putting in the document is part of the contents. So what? You can render it and measure its height without needing to lay out the document. There is no self-reference or circular reference anywhere in the "problem" you've described. The height of the element is an input into the centering problem, but it's not also an output of the centering problem. The positioning of the element is an output of the centering problem, but it's not an input into it.


I'm not an expert on layouters, but I'm pretty sure that in the general case the height of an element does in fact depend on how it is layouted including what elements it is layouted with.

I also believe that's why some traditional UI toolkits have started adopting constraint solvers.

CSS can be frustrating and it was certainly for many years missing basic stuff, punting that to developers to solve by hand - but I agree with grandparent that these problems are not as trivial as they appear.


The height of an element depends on the layout, thanks to overflow


>It’s easy to say “just put it in the centre”, but it’s not as easy to figure out what that means exactly or which solution is best for doing so.

So let’s make it hard even for simple cases. Meanwhile,

  el.centerX = other.centerX
  el.centerY = other.centerY
And it just works without “loops” that simpleton methods like container stacking do have. Did you know that linear algebra has methods to quickly solve that Excel circular reference? What should we do, maybe stop using Excel for layouts?

>The web is one of the most successful technologies in the history of human civilisation.

Amazon is the most succesful e-store in the history. Microsoft is the most succesful desktop in the history. Etc, etc, etc. Being most succesful is a result of many traits, and it doesn’t mean it is maximally succesful, technologically and programmable-y superior or even correct. It was just succesful enough to not break under its weight and split into two or more streams of development. (In smartphones it actually did, and we all know how faster and cleaner phone apps look and feel vs web apps).


I haven't looked into this in any depth but what about modeling it as an equation system? Over/under specified solutions would be an error.


ios layout (autolayout) is like that. I generally prefer it to css, but it's not perfect either.


I used to think CSS was complex and everything was a hack. Then I sat down and actually read about the box model rules, how things like margin and padding affect elements, and how amazingly useful flexbox was.

I've worked with web developers that still don't understand the usefulness of collapsing margins. Developers that think padding is an alternative to a margin and not understanding they are different things altogether. If your solution to spacing something is to wrap it in a new element and add padding then you're thinking backwards. You just add margin to the element you want to space.

I firmly believe the idea that CSS (today at least) is complicated is just people not trying to learn what modern CSS is like. Learn your basics like the box model, block elements, inline elements, etc. Then learn about flex and grid. That right there is like 90% of the knowledge you need to make anything in CSS today.

The way I learned was being given Sketch or Photoshop documents with all the sizes and margins/paddings and told "now make that a website". I really wish there was a learning tool that just had website/website element mockups with sizes and your job is to replicate it as close as possible in HTML/CSS.


> I used to think CSS was complex and everything was a hack

I do web development only occasionally, so I'm not familiar with current best practices and rely on trying to mine the docs for what I'm trying to do and googling for it. I've always very strongly had the impression that while CSS was good at styling, it was hopeless at layout.

That changed with the introduction of flex and grid. Suddenly I'm able to use the layout I want without any real problems. CSS is now usable for both styling and layout.


> I've always very strongly had the impression that while CSS was good at styling, it was hopeless at layout.

> That changed with the introduction of flex and grid.

Half true. Flex and grid are a significant improvement, but "hopeless" was just about always inaccurate. The vast majority of issues people had with layouts pre-flex were because they didn't understand the box model and how block/inline/inline-block/float interacted with each other.

...Unfortunately, not understanding the box model is still a problem, but flex/grid can get people further without needing to understand it.


Devs want composable blocks and design is all about context & harmony, so padding/margin depend on the context, eg I want a flex gap and not margins on elements. Without flex you had to do hacks, like negative margins on the parent row. CSS also doesn't have constraints or relative measurements. For example flex containers without a width can't have equally sized children https://codepen.io/brettdonald/pen/oRpORG). And this is a common theme, you can't elegantly style things based on existing dimensions, number of elements, etc which then you need to work around with media queries or hacks. Also, flex & grid have the same problem as async in JS, when you start building your layout with it, it's turtles all the way down, everything becomes flexbox or grid. That's what I think people complain about, instead of having tools that solve the few dozen common scenarios, CSS gives us thousands of rules that need to be carefully assembled and still not solve the standard layouts.


  > I firmly believe the idea that CSS (today at least) is
  > complicated is just people not trying to learn what modern
  > CSS is like.
You are absolutely correct.


Do you have any specific sources that you would recommend to read on this?


The MDN Docs is my go to place for anything CSS related https://developer.mozilla.org/en-US/docs/Learn/CSS


There's a debate on the purpose of it. They problem is we took our interlinked document space and built thin client applications on it.

Our crosslinked thoughtworld for intermingling intellects in practice is mostly an entertainment and shopping platform.

Really they probably should have split off when it was young ... Replacing HTML with something for the original lofty goals and leave the html/css/js triumvirate for the mainstream use we all see now.

Then there becomes no pretext that there's any intellectual, educational, or documentarian use for the web because there'd be something else, let's call it the Yeb for those purposes. It'd get two way linking, ontological markup, a WAIS like querying system (where the document author explicitly sets the search up separately from the document), etc.

But that never happened and the web has way too much inertia to successfully fork it at such a fundamental level without a monumental multi-year effort so here we are with one set of standards trying to serve all masters at once by layering stuff on top of each other, building a bigger russian nesting doll to stuff our existing web into (could you imagine if say jstor or citeseer required a "yeb browser" because it served content that was fundamentally incompatible with the web standards. Could have taken off in 1995 but not now)

The only engineering results those conditions ever produce is complexity since it inherently, by design, lacks the focus to remove it.


Alternatively, people are trying to do things with webpages that they really weren't meant for, i.e. CSS is based around document-oriented pages so anything outside of its formatting model becomes more difficult. From CSS 2.1 section 10.3.3:

"If both 'margin-left' and 'margin-right' are 'auto', their used values are equal. This horizontally centers the element with respect to the edges of the containing block."

i.e. horizontal centering is easy because that's a natural thing to want to do in a document, but vertical centering seems to make less sense and is thus correspondingly more difficult.


The web is meant for anything you can build with its tools.

That its tools lagged behind what people were building with them is just a reminder that a platform's caretakers have little to do with the creators on the platform.

This goes for everything. I built a forum from scratch that miraculously exploded into a community and culture and drama. 15 years later I look at it and realize it happened in spite of me, not because of me. It doesn't even feel like any of it's mine. I'm a groundskeeper.

I might have built the scaffolding, but who am I to say what it's for once thousands of people have made that decision for themselves?

"No, no, no. The web is for boring documents of <p> and <img>! What are you people building?! The most complicated application I envisioned when I invented HTTP was Encyclopedia Britannica online, and the limits of my imagination must be yours!"


Oh thank you! I very much agree. But I still, as a dev I often feel the urge to keep things simple and wish that I didn’t have to make so many tradeoffs between structure and layout.

It’s many little things, workarounds that pile up given a sufficiently complex/bespoke page. And each of them feel a little bit wrong. Especially when I have to „fix“ things via JS, which fortunately almost never happens anymore.


> i.e. horizontal centering is easy because that's a natural thing to want to do in a document, but vertical centering seems to make less sense and is thus correspondingly more difficult.

It’s because text wraps horizontally and flows from top to bottom. The width is constrained by the window but the height is defined by the contents of the document. This means that if you are trying to vertically centre something in the document, you need to know the size of the document before you can render its contents, but you need to render its contents to know the size of the document.

There’s various ways around this but they all have different trade-offs, hence multiple solutions to the problem of vertical centring in CSS.


> Is this why the web is less successful than it might be?

I'm struggling to understand this question. If the web were more successful than it already is right now... what would that look like?


Web that is a go-to solution for creating UIs of any complexity, not the lowest common denominator that is used where nothing else can.


It is simple to vertically center things in PDF's, since you have a fixed dimension canvas and text doesn't change dimensions due to user preferences or device configuration.

So if you want layout to be simple, use PDF. Of course most users hate to read PDF's online, because they have to zoom and scroll around and so on. So the real question if you want the pain on the producer side or push it to the consumer side.

Producing layout which render reasonably well on completely different devices and screen dimensions is inherently non-trivial.


> Is this why the web is less successful than it might be?

No. The success of the web has nothing to do with CSS. By all standards the web has over-achieved and will continue to do so for the foreseeable future of humanity. CSS is an order of magnitude better these days. Browsers are playing nicer together except Safari. Chrome uses more resources than a triple A game title but sets the standard.


Think of how much extra software engineers get paid because of how difficult it is to do simple things. If it were easy, you wouldn’t need a whole team for a crud web app. If everything didn’t break from updates constantly, you wouldn’t need SaaS in order to feel like a piece of software might still work in 2-5 years. It’s a weird thought, I think I got it from a Jonathan Blow stream


The problem is consistency and lack of direction. There are now sane ways to do almost anything in CSS. But they are not exclusive - they live side-by-side with older, less-sane solutions, many of which don't play nice together. Someone ought to write a "CSS: The Good Parts" book about a modern, sane subset of CSS that plays nice together, covers everything you need, and that the industry could unite around.


I often wonder what is the total time and money wasted the last twenty years because "vertical-align: middle" on a div don't do what anyone think it would and should.

Imagine if CSS had that and nesting and variables from the start :)


After doing the web for 20+ years, I still Google for "vertical align center css" when creating a new layout...

Flex is easy to remember though.


Flex and grid finally made everything make sense. It's like I'm out of Plato's cave now.


it's super briefly mentioned in the post, but just want to highlight that you can center in CSS grid with 1 extra line of CSS:

    .parent {
      display: grid;
      place-items: center
    }
and it's supported everywhere CSS grid is! My biggest TIL of the year.

More 1 liner tricks from Una Kravets here: https://twitter.com/swyx/status/1279674027070504961?s=20


Remember when <center> was all you needed? Maybe with a valign'd table if you wanted to get fancy.


remember when `text-align: center` was all you needed? maybe with a `place-items: center` grid if you wanted to get fancy.

(the vertical centering has always been the not-so-straightforward part. horizontal centering has always been easy. the current CSS techniques are just as easy as the HTML-only techniques you describe.)


CSS "visual formatting" was broken since day 1 due to inconsistency. Take for example "height: auto", a key component in vertical (absolute) positioning.

According to section 10.6.4 "Absolutely positioned, non-replaced elements", "height: auto" is the height based on the content except when top and bottom are both auto and it suddenly changes to the the height of the containing/parent element. This breaks vertical alignment based on content.

Also in the same section, if height is auto, then a top or bottom of auto is calculated, unless both are auto and then suddenly top is set to 0 instead of spreading evenly. For that you need to use margins, but they only work if top, height and bottom are all non-auto.

As a result millions of developer hours have been spent on frustrations, fixups and workarounds.


One problem is there are always cases that aren't covered by these articles. Centering in CSS could be so many things. Center one element inside a another, Centering a css background image . Centering an inline element in a line of text to be centered vertically in the line. They all require different solutions

For inline I'm not sure I ever found a solution I liked. I just wanted something like

This brought to by <avatar> Name

With the avatar the same size and centered similar to emoji faces. I'm sure it's easy but I couldn't find a solution that wasn't a hack of specific sizes (ie, not flexiable/responsive)

https://jsgist.org/?src=2493f4279ba3efb1eb84587238afd3dd


Maybe unrelated but can someone help me point to a good place to start learning CSS by really understanding it at fundamental level.

I have had start and stop bouts of learning CSS several times before and I couldn’t understand it logically like other languages or frameworks for reasons I can’t clearly explain. I avoid frontend programming mainly because I don’t know CSS.


I like how much <center> is frowned upon by the experts, but when you actually inspect how sites are centering things, it's surprisingly common.

Don't worry, I'm not gonna scold HN, I actually don't think it's that bad of a practice as no browser will ever stop supporting it. The experts can look down upon it all they want.


>I actually don't think it's that bad of a practice as no browser will ever stop supporting it

It's not a bad practice to use center because it's not HTML5-compliant (though that's not a bad reason to avoid it). It's bad practice because putting purely visual info in your semantic markup is a bad idea - mixing responsibilities between different layers creates pain points for later work.

In this sense, it's like a GOTO. It'll work well enough for one person on a small project, and you might thumb your nose at the experts who tell you it's a bad idea - but it's a source of technical debt, and the better approach is to just avoid it from the start.


Another perspective:

It's bad practice to constantly change everything every few years, then expect everyone to upgrade to the latest and greatest technology or get left behind.

It's good practice to use code that runs just fine on a 20 year old system.


And yet the change to <center> is not "a few years old". It was deprecated back in 1997 as part of HTML4, because it was never deliberately introduced as a standard tag - <center> only exists because Netscape Navigator was once influential enough to force tags into existence, and it did so, even though the concept itself was flawed.

Centering HTML elements through CSS has existed since 1997 as well, specifically because CSS aimed to make those HTML extensions, that Navigator had introduced, obsolete.

Standards bodies sometimes have to make the tough decision of breaking with the past to safeguard the future. Software longevity is a worthwhile cause, but protecting a 23-year-deprecated, non-standard HTML tag, whose use is bad engineering, is not the kind of hill I would die on.


For the record, I don't think using <center> is a good idea. I'm not arguing for it's use, I just don't believe it's as horrible as some people make it out to be.

Despite the valid arguments against it, it works and it will likely continue to work.


>And yet the change to <center> is not "a few years old".

Also, if you're going to quote someone, quote what they actually said.


What part of that quote did you feel is an inaccurate paraphrasing of what you said? Were you not insinuating that <center> was a victim of change that happens "every few years"? If not, why did you bring it up?


>And yet the change to <center> is not "a few years old".

Changes happen every few years as browser support shifts. That's a fact, right?

I don't know why you're explaining to me the history of <center> as if I don't know it already or believe these changes are new. I mentioned "a 20 year old system" for a reason.

Heck, the fact that it's been deprecated for so long and none of the browsers care is more of an argument for the use of <center>.


>Changes happen every few years as browser support shifts. That's a fact, right?

What does this mean? That browser support is constantly improving, and that over time, new features arise that allow for better architectures and neater code? Yeah, sure. That's not relevant to <center>, though.

That your typical web code is full of rot, and frontend web engineers can be prone to chasing the next big framework? I'd concede that, though I think the alarmism about code rot is very overblown.

That browsers themselves are fast-moving targets in a way that negatively impacts code lifetimes? Hell no. HTML standards are slow. The gap between <center> being deprecated and removed was 11 years. More to the point, the only code that rotted in those 11 years was bad HTML - which mixed visual tags into a semantic markup.

>I don't know why you're explaining to me the history of <center> as if I don't know it already or believe these changes are new.

Because I don't otherwise understand why you would bring up the idea of "changing everything every few years" being bad practice. If you already know that <center> was not abandoned as part of a short-lived fad, then what did that have to do with defending it? Why, when I pointed out that <center>'s demise is not because of the snobbishness of web devs, but instead because it was flawed from the very beginning, both in its invention and its concept, did you start talking about software with a fast rate of change? What was the point you were trying to make - that the fact that <center> is 12 years past its death date, and 21 years past its deprecation date, but people are still making the mistake of using it, is somehow a win for long-lived code?


>I don't otherwise understand why you would bring up the idea of "changing everything every few years" being bad practice

I was just suggesting that breaking things for people who can't afford new computers isn't necessarily a "good practice" and there's different perspectives on these things. Once again, I'm not arguing for the use of <center>, nor do I use it myself.

My main point from the beginning was just pointing out the irony of deprecating <center> 20 years ago, then seeing it used on this very site. Reading your arguments, nestled in between that awful <center> tag, makes the irony all the more delicious.


Ive been developer for 24 years and I can remember the hell it was centering stuff even prior to CSS world.

From the example, I don't like the way he used flex on grids to maintain children aspect ratios, better to use grid's container optiones like justify-items.


This code is very inefficient:

   .autobot > * {
      margin: auto;
   }
Browsers match CSS selectors right-to-left. Because there is a * at the end, this rule has to be matched against every element.

More info:

https://stackoverflow.com/questions/5797014/why-do-browsers-...

https://www.stevesouders.com/blog/2009/06/18/simplifying-css...


From my personal experience, CSS performance isn't really that much of a concern in the world of modern browsers. Maybe IE11 would hiccup on a particularly large page with 1,000s of DOM nodes, but all of the evergreen browsers are ridiculously performant with CSS. I'm not saying you should write queries like that, but if you must (for readability or technical reasons), it likely won't harm your site's performance.


This is a non-issue with modern browsers.


Wouldn't it have been wiser to restrict CSS to document-oriented use cases, accepting that for apps you need Javascript anyway, and then just measure and position elements programmatically? The problem with the discussed solutions in TFA (which is great btw) is the lack of discoverability, and CSS generally solving for the wrong 20% of use cases, bringing unsustainable technical debt for displaying our docs going forward for generations to come. I really would appreciate an attempt to specify CSS behavior, even a subset of it, as a constraint-based formulation or other formal spec; easier said than done, though.


Wouldn't it have been wiser to restrict CSS to document-oriented use cases, accepting that for apps you need Javascript anyway, and then just measure and position elements programmatically?

Measuring DOM elements and moving them around in JS is quite slow. Transforms are fast, but understanding where things are after they've been transformed is hard. JS layout is also somewhat prone to problems with things like browser zoom level, OS display scaling (although I've not seen that be an issue in a couple of years), differences between browsers and browser versions, and so on. Layouts with CSS, so long as you're being reasonably conservative, do work quite well in 2020.


I agree that there's lot of benefits and certain elegancy by sticking with CSS layouts.

CSS transforms are really just an visual effect, not affecting the layout. That's why they are super fast (typically HW accelerated by GPU), but not suitable for defining the layout.

Managing the DOM in JS may be order of magnitude slower but is still fast enough, actually surprisingly fast. It's common to implement 60 FPS animations e.g. in React. Of course the performance heavily depends whether the manipulation causes a layout reflow etc, but generally speaking, DOM is pretty fast nowadays, and most sites/apps are not _that_ performance critical (such as games). Yes, it's not uncommon either that a complex JS app becomes slow, but that's mostly because of inefficient programming / generally bloated app, not because the layout is done by JS instead of pure CSS.

Browsers already have "alternative" APIs to make totally non-DOM interfaces, such as canvas (2D) and WebGL (3d). Nothing prevents to come up with alternative layout/UI libraries written on top of them. I'm sure such a libraries exist. Why it's really rare to utilize non-DOM UIs is probably due to many reasons, i.e. compatibility issues with exotic/older user-agents, devs being more familiar with DOM based solutions, etc.

After all, I think DOM works pretty well even for app-style UIs. Actually, many "native" technologies don't offer as easy responsive layouts, user-settable font-size, etc, which comes almost for free with DOM. There's lof of beauty in the DOM, despite its document-oriented origins.

(Oh, I just typed out some mind flow of mine, maybe a bit off-topic.)


> Browsers already have "alternative" APIs to make totally non-DOM interfaces, such as canvas (2D) and WebGL (3d). Nothing prevents to come up with alternative layout/UI libraries written on top of them. I'm sure such a libraries exist.

I believe Figma renders like this.


>Measuring DOM elements and moving them around in JS is quite slow.

It is not an inherent property of js-controlled positioning. Browsers don’t have direct measuring methods and require stupid workarounds, that’s it. Measuring text layout (most complex thing) in wfh/hfw in js is as fast as in css, because it is just el.getSizeForW(w) and then c++ does the thing as usual. There is no black magic in calculating layouts, it is arithmetic.

>JS layout is also somewhat prone to problems with things like browser zoom level, OS display scaling (although I've not seen that be an issue in a couple of years),

It’s not a property of js either. If a browser provides a stupid internal api that requires manual accounting to zooms and dpi, then css implementation is also prone to that.

>differences between browsers and browser versions, and so on. Layouts with CSS, so long as you're being reasonably conservative, do work quite well in 2020.

The problem is that apps are not conservative, apps want innovation instead of a text layout that spends 20 years to learn a proper vertical alignment.


> Browsers don’t have direct measuring methods and require stupid workarounds, that’s it.

Oh? There are the old-school e.offset{Top,Right,Bottom,Left} etc methods for measuring the DOM stuff, and there's Visual Viewport API (experimental) for more advanced use cases:

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


It doesn’t work correctly until you root your element into the document under a proper div hierarchy (to simulate all selectors) and wait for it to half-render, and then you remove it, which causes entire document to reflow twice, which is a “stupid workaround” part. With this API you cannot “measure” anything, you can only check what was the result of an already computed and pre-heated flow.


> With this API you cannot “measure” anything, you can only check what was the result of an already computed and pre-heated flow.

That's a valid point!


Soo my styling would be split 37% / 63% between my business logic and CSS files, with one million Medium posts telling me how to hack that weird combination from hell into specific looks? That sounds truly horrifying!


Like it's now, then?


I've used this tool fairly often, it will generate the code you need to center based on your browser requirements, etc http://howtocenterincss.com/

I basically only use flexbox now, but even flexbox does some really stupid things I don't get. Like if you want one element to go against the parent's rules of say, aligning left, you set the left margin of the object you want going right to "auto" which will push it and every object after it right. But this can create some annoying problems.


Unlike the other methods, absolute positioning + translating has the advantage that you can not only center the child, but give it a percentage position within its dynamic parent. This can be especially useful when the position should be animated.

https://medium.com/swlh/dynamically-position-and-center-an-h...


Big caveat, this only works when the container has a defined size as you are removing the centered child from element flow


I think as late as 2005 there were moments where I just said "screw this I'm using a table" while everyone screamed about how that's semantically wrong and what you really need is an elaborate series of hacks and misuse of CSS properties.

Flex and grid was the moment I cared about doing things right. Even now I use grid a lot because I find it works as well in 3d as 2d and I get CSS disciples trying to correct me.


It definitely isn't as versatile as the champions of centering from OP's article. But it's a related use case that the other techniques cannot solve. And of course the approach can be varied to some extend: https://jsfiddle.net/31gftbxs/



I've used that site. Doesn't work. Or rather it only covers a small set of cases.


and the relevant HN discussion that hit the front page with over 1000 points: https://news.ycombinator.com/item?id=9405284


I have had this link bookmarked (and used) way longer than i will ever admit in an interview.


https://every-layout.dev is the definitive guide to CSS layout from first principles. Webdev since 1998. This is a hill I'm prepared to die on, so to speak. It should be required reading for anyone doing web UI work.


It's a nice resource, not going to argue that, but most of it is behind a paywall which makes it hard for me to make a go to recommendation.

I lean more towards a flexbox guide [1] or game [2]

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

[2] https://flexboxfroggy.com/


Surprisingly concise and fun article! I hadn't seen the "Fluffy Center" technique before. I'm not sure I really get it though – the video and the text showing different code is only adding to the confusion. Is it 15vmin or 10ch? What does "Word space is gap" mean?


These are useful.

#5 is one that I like. In the past, I’ve had to specify concrete sizes for elements, then set margins of minus half that value. This is better.

I would like to be able to do the same type of thing for background images, but this technique could give me the same effect.


I always follow this personal rule for centering:

- Buttons and stuff that should stay the same with font increase: padding with ems

- Everything else: flexbox

Flexbox has made everything so easy.


Just use "<center>data</center>"

seems to work every time.


Wow VisBug is really interesting. Never heard of it.


Did not even hear about some tips


What on earth did I just read?

"Pop and Plop"?

"Gentle Flex"?

"Autobot"?


[flagged]


"I was ignorant of this unit of measure so the author is an asshole" is spectacularly rude. What is your solution to specifying that a column should contain on average n characters in CSS? With your reaction, I'm sure you must have a solution than is simpler than just using the basic unit measure that CSS provides? Because the author isn't being "clever" or trying to be "cool" by just using the basic API provided.


It’s not enough to explain just only css, we also need an equivalent using css frameworks such as bootstrap, material, and tailwind, since most use frameworks these days


An article about CSS shouldn't need to mention frameworks - it's the framework's job to explain how to use the framework. You wouldn't expect an article about lists in C to explain how to use arrays in PHP...


Are you implying that using a css framework somehow restricts/prevents you from also using normal css in some places?


no. i was just simply implying it be nice if they also had a reference on how to center (both vertically/horizontally) using some of the major CSS frameworks built-in way 'without' resorting to raw CSS.

kind of like a cheat sheet. because the problem i face is that there are just too many ways to center things and wish there was a most recommended method. i come across many articles explaining how to in raw CSS, but not too many using frameworks.

i typically jump from one css frameworks to the next (bs4, material, tailwind) and writing custom css is usually frowned upon if there are already a way to do so built-in by the framework. but it's hard to keep up with these changes so thought it'd be nice if there were some guides or articles for them.


honestly cannot tell if this is sarcastic


At least for bootstrap, most of the relevant classes are essentially aliases for flexbox, so I don't see why it would be much use.


I know it's not the trendy thing, but <center> has always done exactly what I wanted without much fuss. Even if it's technically depreciated, it's in such widespread use that no sane browser would ever remove support.


Every article about CSS centring is about centring horizontally and vertically. <center> only does horizontal.


The web development "community" seems to love reinventing increasingly complex solutions.


No doubt there's overlapping complexity in web technologies (e.g. flexbox and grid), partly because we can't re-invent everything from scratch. Multiple players probably also play big role here, single-vendor technologies are easier to get right.

But, often the problems are also non-trivial. The web platform is really diversed, there are user-agents everywhere from mobile phone to smart tv and everything between, with extremely varying input methods (touch, mouse, etc), resolutions, pixel densities, performance, etc. Some of the devices are never updated, running a decade old browser. I don't think any other technology faces similar challenges. Actually it's amazing that things work as good as they do.


<center> and the solutions in this post are not equivalent ...

The HTML center tag only horizontally centers the contents which you can do with the simple CSS: `text-align:center` [1]

The examples in this post center horizontally AND vertically.

[1]: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/ce...


text-align:center does NOT entirely replicate <center>. And has been a source frustration for many.


that's fair, but <center> and this post are still not equivalent at all.


Nah, that's just the javascript nuts. We're much saner in CSS land.


You probably wrote tongue in cheek, but it's a good point.

The fact that there are "JS land" and "CSS land" is one of the problems. There should be better integration between the two, eliminating the need for "hacks" such as replacing stylesheets by JS styling (popular with React, for example). Writing variable-based dynamic CSS is too hard. SASS and other variants don't solve the problem because they are compile-time, not runtime technologies.




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

Search: