How to center in CSS

How to center in CSS

I knew this would result in using table cells...

That this site even exists speaks volumes about CSS.

Why don't they just add a align:center property? Every person new to css has trouble with this.

Back to tables! We've come full circle!

CSS was created by people with absolutely no understanding of modern web design.

Apparently the above site was as well.

Because we want to separate between content and presentation: HTML describes the content, CSS describes the presentation. A "table" in CSS only means it uses the same layout algorithm as a HTML table; a "table" in HTML means a data structure with rows and columns.

Tables still have their use. Just don't go overboard with them.

I find it hilarious when people try to use CSS to build, what is essentially, a table. Just use a table if you need a table!

If you hate CSS in 2015, your brain would have imploded if you were trying to use it in around 2000. CSS of today, despite its shortcomings, is incredibly cross-browser compatible compared to back then, with many powerful features. It's by far not perfect, of course.

This is why I hate CSS.

(╯°□°)╯︵ </ǝlqɐʇ>

Everyone knows that CSS and <div/> were invented by hipster trolls. Just use <table/> and get back to work already.

There's a certain threshold of bullshit beyond which I just assume the site's designer is attempting to hurt me. Suffice to say, this has passed it.

From the start, the whole of HTML rendering and layout can be thought of as the mish-mash of two schools of thought:

People who want to make publications, like print People who want to make applications, like desktop software

Since then we have grown from nothing, a third camp where people want to further the use of a browser's broad base of capabilities as its own medium:

People who want to make web pages.

If you ask me, the CSS standards folks are approaching things from a print perspective. The actual precise positioning of elements in a page takes a back seat to use cases like ensuring that text flows around islands of images and embedded quotes. At the same time, some concessions for web applications are shoehorned in, but they get to compete with the same layout engine so the result is very gross.

And somewhere in the middle of all that, the simple task of aligning any element either vertically or horizontally was left out. For the longest time, people used the <center> tag as a crutch, so perhaps 12+ years ago, people weren't as vocal about this hole in the CSS spec as they should have been?

Css has its faults, but you can't tell me the endless nested tables and clipped images were a better system.

I just don't understand why in 2015 css is so convoluted, disjointed and generally unintuitive.

For what it's worth, that was written back in 2008.

However, even back then I disagreed with his opinion. Constants and being able to do math is a very simple concept. What makes CSS complicated are the amount of properties, their possible values, and the way those things interact with each other (e.g. float affects display).

Tables come with a lot of baggage.

And a simple centered element is not a table but we have to use them anyways because it is the only element which can use centered vertical alignment for unknown sized divs.

Congratulations, you're part of the problem.

You should use flexbox.

It's like a variation of the sudo xkcd comic.

"You are not going out dressed like that!"

"You can't tell me what to do!"

"You are not going out dressed like that !important"



I swear this is like 90% of CSS logic.

I'm imagining Clippy popping up in my editor now, saying "I see you're trying to center stuff with CSS. How can I help?"

Seriously though, great idea. It could probably use some browser compatibility check boxes (which mostly boils down to "Can I use flexbox?"), but it's already pretty useful.

Thank you! Someone understands that just because the word "table" and "cell" shows up in the CSS does not mean we're somehow going back to 90's-style layout.

Yeah, fuck that. Use modern CSS and screw IE8.

Vertical and horizontal center with arbitrarily runtime-defined sizes.

/* prefixes and pre-standards flex left out for readability. Use SASS, LESS, or some other CSS abstractor for macros to dirty this up */ div.container{ display: flex; align-items: center; align-content: center; justify-content: center; } div.content { flex: 0 0 auto; }

And if you can't drop support for IE8, lobby for "latest and last" support only within your org. No progress is ever made if you just let people's old habits live.

Source: was able to successfully lobby for this policy. As a result, my app can leverage fonts, SVG, MathML, flexbox, namespaced XML, XHTML5, XSL, DOM templating, canvas, and anything else supported in IE10+. Meanwhile, with just a little bit of CSS abstraction for prefixed rules, most things work in IE9 as well, with no guarantees. We get very little complaints, and they're easily redirected by a quick, "we don't support IE8 or 9 anymore; our recommendation for best performance is to use Chrome, but IE10+, Firefox latest, and Safari latest will work for you."

Many of our clients are companies, and there is literally no reason to kow-tow to their lazy-ass IT department. To this effect, we have a non-negotiable policy that development intended to support browsers outside our policy costs double. Requests for legacy support will cause existing development work to be charged double retroactively. We then convince them that it will be cheaper to get their IT dept to fix the problem.

"Back in 2008". I think in 2008 many people were well aware of how awful css and html really were at that point.

CSS first came along in '96. People were still using FRAMES back then. Then we went through the whole "tables for ALL the things" revolution. Then we finally started using CSS. At that point it was too late. By the time it had wide adoption it already sucked.

I do agree about the issue of origin. Just look at what happened with the W3C, XHTML, and the creation of the WHATWG. I think this is why people started embracing plugins like Flash. You could finally get a consistent result across browsers without fighting things that have been inherently broken in the language we use to build sites since the '90s. Being a web dev sucks. Source: am web dev.

Yes. Anyone who says "Don't use a table for tabular data" is clueless no matter what perspective you take.

reminds me of this mug

Yeah, CSS has largely become an overcomplicated mess. While the basics are very easy to learn, it's difficult to become competent in CSS because there's so many weird edge cases and ways for unexpected quirks to appear. It's made worse by the fragmented browsers that don't always handle things the same way.

The issue of centering things, however, is particularly weird. It's been a major issue for a long time. Pretty much everyone has issues centering things at first. It's like a CSS version of monads.

Even flexbox isn't a very good solution, IMO. While very general, it's rather unintuitive.

Always fun to remember that the web was invented on a NeXT box that came with a development environment that could produce layouts with drag and drop that are still impossible in CSS without loads of javascript.

You're right. I'm just saying if you need a table, as in you want to display elements in a table structure, don't try to reinvent the wheel. Just use a table.

But unfortunately, the only person who ever knew them was a wizard who lived on top of a mountain, and who has since mysteriously disappeared. oh


But <div/> is not valid HTML5... ;)

How about, "use IE 6.crusty for your shitty old finance app and use Chrome for accessing the Series-of-Tubes."

To be safe, configure IE to use a proxy which only allows access to Shitty Old Finance App. Heh. SOFA. Gonna use that...

It is fantastic. After a decade of "No! Don't use tables! You can do your layout without tables. If you think you need to use tables to organize your layout you are just doing it wrong." to "Just make all of your layout elements into tables and table cells. Just make sure you use CSS tables and not HTML tables. Because."

HTML6: Introducing the <grid> tag.

Muphry's Law:

Articles on writing are themselves badly written. Any book devoted to editing or style will be internally inconsistent. If you write anything criticizing editing or proofreading, there will be a fault of some kind in what you have written.

I think you may have answered your own question just a bit. I could say the same about any terrible programming practice. "What's so bad about global variables?" or, "What's so bad about goto?" You could answer any such hypothetical question by saying "I'm not some fancy <insert language here> guy, just looking to get the fuck outta there and back to my real job, and <horrifying feature> seems to do that for me."

The worst thing about tables is that, like the font tag, they stuff all that formatting into the HTML itself. Only worse, they actually force you to completely restructure your content based on how you want it to look. This makes it much more difficult to rearrange things later, and when you do it, you're probably going to have to change every piece of code that touches the page. CSS solves that problem.

Look at Reddit -- subreddits can have different skins, sometimes very different skins, without having to change any of the code -- all the Python on the backend, and all the JavaScript on the frontend, can stay exactly the same. You just change the CSS, which just changes how things look, not how they behave. If Reddit had been built with tables, quite a lot of that would be impossible -- even really simple stuff like the fact that the "comments / related" links are below the banner in /sub/explainlikeimfive, but beside it in /sub/programming.

There are some perfectly legitimate uses for tables in web design, but you have to understand, people were using tables for everything. A site like Reddit would be one giant table with a row for the strip of subreddits at the very top, then a row for the top banner area, then a cell for the content. In the row for the top banner, you'd have another table with a single row and two cells, one for the menu on the left (including the logo) and one for login/logout/etc on the right. And inside each of those would be a table, and so on.

They were much quicker to make a design that sort of looked okay, but once you did, that design was totally inflexible, and a change that looked simple could take days. CSS takes a bit more to get started, but seriously, you can make a site that seamlessly transitions between desktop and mobile versions, where the only difference between the two versions is CSS, and even the logic that switches between the two is pure CSS. Which also means that a huge chunk of your look and feel can be done by a designer, so you can get back to your real job and not have to care about the endless redesigns your site will have to go through.

That said, it still sucks. It just sucks a lot less than tables, in the long run.

I came here assuming that article was about exactly that. Instead it's using some outdated 2006 CSS code to center elements when it's 2015.

.flex { display: flex; justify-content: center; align-items: center }

Flex wraps text in an element for coherent behaviour. It's that simple.

Not in all market segments. In e-commerce, I see really weird distributions in user agent for certain products.

In my opinion, using HTML to create full-blown applications is an abuse of the technology. Everything about the way HTML is designed screams "document" (we even have dedicated tags for "paragraph" and "emphasis"). All of the web applications that we know and love rely on an assortment of hacks that were eventually enshrined into the spec.

The only reason we got to where we are is because people figured out that the web browser is the closest thing we're going to get to a truly cross-platform environment.

It's hacker news, do they ever not flame war there?

Well, the poor design sense of the person who wrote the article is at least 50% of the point. Although modern web design is very unlike what web design used to be like, design as a discipline was certainly a real thing at the time the article was written.

The article is from 2008 and its title is "Why 'variables' in CSS are harmful". Now, I don't actually care about variables in CSS and that isn't the point I wanted to make by linking to this article. But the author gives several arguments for his point, one of which is that using variables to make stylesheets shorter is not necessary, because:

Very few people (only professional designers, it seems) write style sheets longer than a hundred lines.

(Emphasis added.) There is also this boxout:

A bit of statistics on the W3C site reveals the following distribution of sizes of style sheets:

number of CSS style sheets: 25725 number of non-empty style sheets: 24805 largest style sheet: 4872 lines (generated by an early version of FrameMaker) largest hand-written style sheet: 1462 lines (bought from a Web design company) average non-empty style sheet: 54 lines

The distribution is as you might expect, lots of very small files, very few large files:

Half the files is less then 7 lines. 90% is less than 163 lines. Only 0.6% is longer than 500 lines.

The authors who write on this Web site site are probably more careful about the structure and re-usability (and download speed) of their documents than the average Web author and there are indications that the average size of style sheets on the Web is two or three times higher. That is still small for computer code, though. Although it doesn't fit in one window, like the average W3C style sheet, it doesn't take more than scrolling once or twice either.

(Emphasis added.) Notice how the needs and usage patterns of professional designers - the people who most need CSS to be usable in order to do their jobs - are specifically ignored and downplayed. Meanwhile, the needs of the article author and the W3C website itself - whose needs are admitted to be extremely simple compared to most people, and who apparently have quite poor design sense in the first place - are viewed as typical, and held to be more important.

Under these circumstances it's not at all surprising that CSS turned out to be as impractical as it did.

As an aside, I never understood why some elements can't be self closing even when it makes perfect sense. <div /> is perfectly valid XML and IMO, it should make sense in HTML, too. It should be treated the same as <div></div>. There's plenty of reasons to make empty divs, after all (most commonly for generated content).

Script tags are also a biggy. Why can't we do <script src="script.js" />? Why is it necessary to use <script src="script.js"></script>?

XML totally allows you to have tags that may be self-closing or contain values. So why doesn't the much laxer HTML? It strikes me as a strange and unnecessary limitation (especially since it can cause things to silently break).

As an aside, despite being invalid HTML 5, it seems that some browsers (at least Firefox, which I just tested with) are perfectly happy to support this invalid HTML (there's a ton of things that are technically invalid but all major browsers allow).

There's a new feature called flexbox that is already supported in most browsers. If you hate floating layouts like I do, it's worth to give it a try next time you have to wrangle with CSS.

To be honest, there's plenty of threads with 0 comments.

Even 5-10 years ago it was bad. CSS3 encouraged MS to at least do some work on their bad compatibility.

For an interesting discussion bordering on a flame war, see Hacker News' take on the submission:

<div style="display:table-cell;vertical-align:middle;"> <div style="margin-left:auto;margin-right:auto;">Text Content</div> </div>

It's ... beautiful!

In my opinion, using HTML to create full-blown applications is an abuse of the technology.

Having done this for 15 years now, I agree completely. Really what people want in this space are all the properties of a web browser as an application container of sorts, aside from HTML+Javascript. If the major browsers supported an alternate set of standard technologies for apps, the industry would adopt it in a heartbeat.

The only reason we got to where we are is because people figured out that the web browser is the closest thing we're going to get to a truly cross-platform environment.

Exactly. It's easy to take this for granted. If you subtract HTML+JS from the equation, here's what any browser gets you:

unparalleled platform independence networked content delivery model huge, almost universal, install base standards-based implementation sandboxed security model lock-in-free adoption massive knowlege base, and talent pool to support it for app/page/web development bottomless support base, including unlimited free third-party product support

Is it any wonder that we're in this mess?

threw this together, its similar to what I actually use in production. I didnt bother making it too pretty, you can see how you would handle that though

responsive at 700px, you can easily tweak that

You can also use javascript to set the titles on all the rows, but with gzipped content this is a marginal increase in content size even just hardcoded. You can also deal with multi-line data by wrapping each "group" of rows in their own tbody, and styling accordingly.

I stopped making webpages when table layouts came out of fashion...

CSS positioning was a pain in the ass

Hacker news is pretty much the best example of pseudointellectual smugness out there.

"You are not going out dressed like that !important"

I guess you could say that their position is absolute on that matter.

The best part is how it includes a java applet on his main homepage.

very surprised that flexbox wasn't at least mentioned:

The idea that you could separate content and presentation with HTML and CSS is wishful thinking. HTML is presentation. CSS is presentation. If you were describing the data on the page, would you use a bunch of <div>'s? Clearly not. Both HTML and CSS are too weak to actually separate content from presentation. The fairy tale was that the programmer could write the HTML and then a designer would write the CSS. That model clearly does not work. XML + XSLT did get that architecture right, but the practicalities totally wrong.

In general the value of platitudes such as "separate content from presentation" should be critically evaluated. Those things become like a religion, and people dogmatically subscribe to those kind of ideas whether or not they actually help in practice. It resembles cultish behavior, where not adhering to the dogma is viewed as unclean or even immoral. Instead we should continuously evaluate whether the benefits outweigh the costs.

"has become"? Sorry, but the reasons for the messiness are all 20-years-old. The new additions to CSS are actually very competent. And we can't use them anyway, because IE. As always.

lazy-ass IT department.

Hah. Not a sysadmin I take? :-). Try finding a good balance on easy-to-use, lastest-and-greatest and supporting-that-old-finance-web-app-that-we-depend-on.

I remember trying to make a page that had three columns with individual solid background colors with something vertically centered, the background colors extending the length of the longest column, and just basic formatting working OK.

It's like 18 years later, and I still don't know how to do it. I just decided doing a PhD in machine learning and writing kernel drivers in my side job was way easier.

HTML describes the content, CSS describes the presentation.

That has never and will never be true. They are way too tied up with each other.

That would make too much sense.

I hate native 10x more than css. You want an app that runs on Android and Apple? Code it twice, in a completely different environment, in a different programming language, and have Google/Apple controlling whether they allow your app in the store. Screw that. I hope native slowly dies and most "apps" are just websites. For 90% of the apps out there (other than games) a "web view" would probably be sufficient.

IE 6 and 7 combined account for ~1% of the browser user share.

It's the reason I prefer doing "backend" development... I still love web development, as long as I don't have to do CSS.

CSS was created before modern web design

But yeah, more recent updates did miss some opportunities.

Why? No, seriously, why?

Could you post what this website says? It doesn't work on phones.

Could you post what this website says? It doesn't work on phones.

Good thing no one uses IE9.

Eh, just use flexbox.

text-align: center; has always existed in CSS to handle what <center> does. The biggest problem has been vertical alignment, for which there are various solutions, but none of which works in all cases.

The stated goal is to separate content and presentation, but the element designated for content is better at presentation, and the element designated for presentation makes it impossible without jumping through hoops.

I also think that one of the main issues is that there is no encapsulation whatsoever. Everything is global and you have to come up with some conventions to stay organized. CSS doesn't provide anything to help with that.

The CSS Scoping Module Level 1 is supposed to help with that in the future. However, I'm not really sure if this is a good way to handle it. I guess I need to use this stuff a bit more. Right now, it just feels very heavy-handed.

Anyhow, most of CSS' issues stem from the fact that it's a language with its very own category. It can't learn from other language's mistakes and it also can't borrow things from other languages. So, the only source of inspiration are preprocessors which will never do anything radically different.

With CSS you can make changes to your entire app's layout by just changing the CSS. And with HTML tables you can make changes to your entire app's layout by just changing the HTML.

Anyway, the argument of "you can make changes to your entire app's layout by just changing the CSS" is inherently flawed. Yes, you can make changes to your app's layout without altering the HTML. The question is how often are the changes you want to do possible without changing the HTML. Often you'll end up with "we want to move this element from the header to the sidebar, so then we need to update both the HTML and the CSS", or "we want to change how these elements align, so we need to add a helper-div around them and updating the CSS".

Separating layout from content as much as possible is a good thing, but CSS is not doing a very good job of solving that problem. The layout hierarchy is still defined by the content hierarchy.

Anyway: using tables does not mean that you are not using CSS as well. Just because you are basing your layout on tables does not mean that there are fewer changes you can do using CSS than if you had done otherwise.

For real? From what I've seen, most commenters are respectful and anything reddit-level snark or shitcomment gets buried. I mustn't spend enough time there.

Sadly this is truth. Your main market is rural users? Get ready to make a tiny site that'll download quickly on their slow satellite / dial-up connection. Also their computer is ancient.

Hell, I remember writing all my sites with a nav frame, and a content frame. Menu on the left, content on the right. Two different pages though.

But being a web dev now sucks less than it has in the past though, because we have access to such great libraries that sort of smooth out many of the browser compatibility issues.

The core reason is because CSS was not really created to do layout in the first place. It was created in an era when you made the layout with tables (that do have a center property), and set the text styles, colors etc. with CSS. The two main ways we use to layout with CSS, float and margin: 0 auto, are either outright hacks, or edge-cases of a layout algorithm.

The CSS people saw this, and created display: table. Read some interviews from 5 or so years ago, and you'd think it'll be the solution for layout in CSS. After all, it gives people what they wanted! The old table layouts, but with CSS! And yes, you can center, both horizontally and vertically with display: table. Sort of. Unfortunately, tables were never really good for layouts either. They have this complex, bizarre algorithm to calculate the dimensions of cells, that usually ignores your "width/height" properties, and it creates some of the weirdest, hardest to solve CSS bugs I've ever seen. Because, surprise surprise, tables were meant for flexible tabular content, not for layout.

So they created another, slightly better, but completely unrelated set of properties, called flexbox. It can also center, in more than one way. But it's not supported by most modern browsers, and honestly, I'm not sure it'll be the silver bullet either. And in the meanwhile, people devised even more tricks, like using absolute positioning in conjunction with the CSS3 translateX/Y transforms, or if you want to center something horizontally, using display: inline-block and text-align: center.

The result is that there's not one, but something like four or five ways to center something, each relying on a different layout philosophy. So it's not really a problem that could be solved by adding yet another center property. Most likely, we need a serious rethinking of how CSS works, or some way to bypass CSS altogether, and create some better layout language.

Well this is one reason why Flash was so popular. You could actually write an application in it. No idiotic "document" stuff. They even built a toolset (Flex) specifically for app development. Unfortunately flash had all sorts of other problems (like security).

Building an app in HTML sucks. Positioning and scaling things sucks, single-thread issues in JS suck, inconsistencies across browsers and platforms suck, and the native desktop input controls are terrible (most mobile browsers have better implementations of a lot of them).

I just don't understand why in 2015 css is so convoluted, disjointed and generally unintuitive.

Powerful forces pulling in the spec in competing directions while needing to be compatible with the historical cruft. Wait until you try using meta tags to mark your HTML documents for crawlers – that's a nightmare and a half. At least with CSS they decided to make a horrifically unified and cross-compatible system.

Cascading behavior also makes CSS fiendishly complex, outside of the sheet you're writing. If you're a programmer, you're used to thinking beyond the code that you're writing. If you're a publisher or "webmaster", the idea that you'd want to break up styles into little pieces that interact with each other, or override one another, is not how you're accustomed to doing business. You'd much rather use Dreamweaver or InDesign than wrangle stuff like that.

I only mentioned that because the author might have changed his opinion in the meantime. Also, preprocessors weren't that popular back then. Sass appeared in 2007, for example.

Well, he doesn't really seem to be involved with web stuff anymore. He probably doesn't give any fucks either way.

Trust me, if you ever want to create a new website, you don't even want to consider to support IE < 10. Unless you work for a customer that insists on that.

I can write a beautiful responsive table in a tiny bit of CSS, less than it would take me to do the same without using a <table>

Mainly, thanks to ::before { content: attr(title); }

The thing is, true CSS centering vertically and horizontally with arbitrarily sized content has been possible for a very long time (with perfect browser support) with the use of a single div tag and a couple of lines of CSS without relying on table hacks

EDIT: Here's my proof

EDIT 2: Something else I whipped up that may be of use: centering columns with arbitrary content sizes.

Wow, even for 2008, that guy seems clueless. And the lengths of the stylesheets he mentions seems comical. A recent project I've worked with has a very minimalistic appearance and is not a very large site, yet the LESS stylesheet is about 500 lines.

That's not even considering major sites and projects. The compiled and uncommented Bootstrap stylesheet is over 6000 lines.

I guess you are OK with throwing away a significant percentage of visitors. Some sites actually are businesses you know.

This is why I hate web development and take native over web when given the choice.

You really don't know the reasons not to do that? And the people you worked with didn't either? The point is that with CSS you can make changes to your entire app's layout by just changing the CSS. If you have a table, you are going to be going through and changing every table. Or a lot of tables anyway.

Android and iOS are just two of many native environments out there. Besides there are portable native solutions, based on approaches older than the web.

Also not every application needs to be made portable.

Finally, HTML whatever will never match native, it will always be playing catch up with OS features while offering a layout engine for documents, not applications.

I stopped making webpages when table layouts came out of fashion...

Heh. I usually argued "but wait a minute... if the layout is easy to do with tables and a complicated messy pain in the ass with CSS... AND it renders just as fast... WTF? Use tables..."

Some people would respond "Yeah. Let's do that."

Others would scoff and ghasp in horrror and hemm and haw about 'css being cleaner' or 'ha! You rube! You hack! Tables are the old way.'

And I'd counter argue "But... Give me a good reason other than 'the old way'. You can't say 'being cleaner' because your hacky css way has lots more code spread out in different files." Usually they couldn't provide a compelling argument.

And ultimately it didn't fucking matter because anything we built back then has long been gone... reverted back to its constituent electrons... lost for all future ages...

The argument was full of sound and fury, and ultimately signified nothing.

Also people with no concept of progressively improving an API in a concise and clear way. There are trivial things that CSS does well, and trivial things that make no sense. Overflow:hidden is used stretch the holding div around in internal one. Why? Also there is always some odd combination of attributes to do so simple things.

They wanted a feature, they added it without taking the time to refine the spec. Now companies that make browsers and struggling with custom tags and making sure everyone's output is the same (even IE started to pay attention)

Flex box is supported fairly well in modern desktop browsers. But on mobile devices, it's a real pain in the arse to work with, especially where customer requirements demand that you support Android 4.0+ (or worse) and where even the same OS version on different devices can exhibit vastly different bugs.

And so that other people don't make the same assumption as me: this is NOT referring to bootstrap-style grid-based page layouts. This is much more interesting.

Do you have an example of these CSS-impossible layouts?

I don't do web dev, but maybe you could let us know what "programming" means to you then.

They're not "CSS tables", they're just display properties that render stuff in the same way as tables have classically done. Gives you the functionality without screwing with the semantics. It's obviously a bit dumb and hacky and no one would realistically design these things like this from the ground up now... but meh :P

The bad thing about the css display table properties, though, is that some of the weird shitty behaviour (like stuff related to positioning) is also carried through and so you can get some weird behaviour as the browser is really using it's table layout stuff internally which is not always necessarily what you want.

Honestly, I'd like that better than a table. Say do a <grid><coor x=5 y=2>data</coor></grid>. Way simpler and easier to visualize.

unfortunately you're not wrong. the only reason I am still fixing shit in IE 7 & 8 is for one of our retail clients, for their market in China.