Hacker News new | past | comments | ask | show | jobs | submit login
CSS Absolute Centering (codepen.io)
526 points by nvk on Aug 10, 2013 | hide | past | favorite | 221 comments

I have just started doing web programming in the last month after several years of applications programming.

It feels like to me, and someone please tell me why I'm wrong, that the amount of hackery that goes into making webpages look the way web designers want them to is astounding. I google for solutions to various problems and the top rated comment on StackOverflow says "...there isn't a good way to do this in CSS, but here is this hack...".

I feel like somewhere in the universal programming ether there exists a beautiful unification of HTML, CSS, and JS that doesn't rely on any ugly hackery, and it's just waiting to be found and start a brave new world of web programming...

As someone who's done an insane amount of front-end programming, you're entirely right.

Sometimes I wish I could get back all the brain cells that I've wasted on the hundreds of "little tricks" you need to know to get things working -- and then working cross-browser.

Short answer: CSS is just a horribly, horribly, terribly badly designed language. It's the absolute worst. Don't let anybody tell you otherwise. It's that, it's what we've got, and it is awfully powerful in many ways. But it's complete rubbish in others, which include a lot of incredibly basic layout things.

crazygringo is absolutely right.

When the committee responsible for CSS started working in the late 1990s, it seems to have lacked any members who knew anything about layout. Certainly, the browser was a new challenge, but automatic layout engines had existed for decades by that point. TeX, for example. While it is a beast, I have usually found it far easier to get its glue-and-boxes model to do what I want than wrestle with CSS.

To make matters worse, the CSS people considered it a badge of pride that CSS lacks programming features. Allow variables to represent colors so we don't have type #f0c450 all over the place? Nesting constructs? Perish the thought!! That would make it look like a programming language, with scopes! As a result, we now have LESS and Sass which plug up the worst holes, but do nothing about the fundamentally brain-damaged layout model.

You're comparing a layout engine for print where the creator has control over all aspects of the presentation (font size, page size, etc.) with CSS where the content is displayed in an environment where the user is in control of many of those? Apples to Oranges. Pretty much all the things that are difficult to do in CSS have to do with this uncertainty and lack of control.

For example, centering in CSS is trivial if you're only doing it for one viewport size, font, font size.

It's true that it is harder to design a model based on different viewports and so on. However, this does not excuse the ridiculous shortcomings of CSS, especially in this case.

CSS doesn't really have vertical positioning within arbitrary boxes, which is insane if you think about it. This shortcoming has nothing to do with viewports or fonts or whether it's screen or paper. After all, the rule "box B is to be vertically centered within box A" is not dependent on a particular medium such as print or screen. The rule "box A is to be 100 pixels tall" adds medium-specificity, but that's different.

Rather than providing rich high-level rules to create simple, responsive layouts, CSS makes one jump through hoops to accomplish trivial things like vertical positioning, and gets mired in finicky micro-details and a cumbersome, inflexible layout model. It breaks down quickly; for example, only recently, with the introduction of "box-sizing: border-box", has it been possible apply percentages to box sizes that have padding. (Before, if you had two boxes with "width: 50%", they would wrap if you applied padding.)

As an aside, I am personally not convinced that the CSS promise of separating presentation from content has paid off. In any serious web app, the DOM is visual, and separating CSS from the DOM makes no sense. It's useful as a way to organize code and to share style rules, to be sure, but those benefits don't come from content/presentation separation. I wish we had an inverted model — a visually oriented language concerned only with presentation (think SVG, only not limited to vector graphics), with a separate data language concerned exclusively with data.

As I said, the browser is a new challenge, and I was referring exactly to the problem of presentation flexibility. However, I'm pretty sure that the boxes-and-glue model can handle flexible viewport and font sizes as inputs from the browser, rather than specified by the user in terms of page size.

CSS has boxes, more or less. It does not have glue in any meaningful way, i.e., it does not give a direct way to specify what happens in between the boxes. Pretty much all the things that are difficult to do in CSS have to do with the difficulty of describing what happens in the negative space.

You should distinguish between whether the syntax and general principles of the language are horribly designed or whether the current language features are lacking. They're very different critiques. The former results in people saying we need to completely scrap CSS and find a new way to layout pages. The latter results in people putting more pressure on and getting more involved in the CSS working groups and browser implementations to get new features pushed to consumers.

Well, there's nothing inherently wrong with the syntax or structure of CSS (and things like LESS make it even nicer).

I'm talking about things like the way "floats" transformed from a way of wrapping text around pictures (good) to a general-purpose layout mechanism (disaster).

About how there's no way to put a footer at the bottom of your page that stays at the bottom if your content is short, but gets pushed down if your content is long (the normal desired use case).

About how the only way to get two columns of equal height, but that expand to fit the text, is to use a <table>, but that this is supposedly disallowed because it's "unsemantic".

About the complete disaster that float-clearing is, yet how it's central to almost all modern CSS layouts, and fixed only by bizarre byzantine hacks like "clearfix", overflow:hidden (which breaks other things), or the classic "<div style="clear:both;"></div>" which needs to be peppered throughout HTML, negating the whole supposed distinction between HTML and CSS.

And finally, the fact that the width of an element doesn't include its border and padding, making for nesting div's that include border and padding much more difficult than it should be. (Although this is, of course, fixed in newer versions of CSS.)

In the end, it's not really "current language features", but mainly the disastrous decision to adopt floats as a basic layout concept, instead of grids/columns/etc. (Which is, of course, why so many people wind up using <table> in the end, which has its own problems...)

No one ever really decided that floats were the way to layout columns as far as I know. It's completely about "current language features". The standards group was just too slow to implement a decent alternative so we had to use floats. But flexbox[1] is the solution to lots of the problems you are mentioning, and it's almost support in all modern browsers, so very soon we can start abandoning floats and absolute positioning in our layouts.

Meanwhile, CSS is still a well-designed language in terms of syntax and principles. We just need a few more features that weren't in the original spec as new uses for the web emerge.

[1]: https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Flexi...

I actually wish that CSS didn't have so many different ways to write a rule. Have just one way to write a rule and enforce it strictly.

In other words, instead of being able to write any of these

  padding: 0 0 0 0;

  padding-top: 0;

  padding: 0;
Just settle on one (the first one in my opinion for this rule) and get rid of all the other alternatives.

The first one (and the third one, which is closely related) doesn't provide any mechanism to override a single of the padding settings while inheriting the rest.

If you could only have one mechanism, and you weren't going to lose significant functionality, it would have to be the longhand padding-top, padding-bottom, etc., set.

But I think having the shorthand rule is worthwhile.

I didn't think padding was inherited?

The reason I chose the first example over the second is that, if you only ever specify padding-bottom for example, what are the default values for the other unspecified padding properties? This is why we have the CSS reset technique and normalize.css (more hackery).

I would make it mandatory that you declare all four values for the padding rule to remove any ambiguity. That would also mean eliminating shortcuts like

  padding: 5px 10px 15px;

  padding: 5px 10px;
I think having shorthand rules just adds to the ambiguity and complexity of CSS, because, as you rightly point out, each of the variations has a subtly different meaning from each other. This is not a good thing (in my opinion :-) especially when you consider how lengthy and complicated stylesheets are nowadays for many websites.

It's not about inheritance, it's about specificity. If you have a generic module that specifies

  padding: 5px;
And you actually the bottom of your element to have more padding, you need to be able to do adjust the bottom padding independently

  padding-bottom: 10px;
Otherwise, you'd be required to tightly couple your our padding requirements with the defaults of the original module

  padding: 5px 5px 10px 5px;

CSS requires you to do that in plenty of other places (e.g. if you make your border 1px wider you have to make the element it's on 2px narrower.)

If you set box-sizing: border-box [1], you don't need to worry about the latter.

Even without border box you can achieve that quite easily (since the conceptual border-box 100% is the default for blocks); you simply need more wrapper elements.

If only that worked on all the browsers I was required to support...

How about if you want to override just one part?

It doesn't make much sense with "padding", but for something like "border: red solid 2px;", how do you override just the color if you don't have the individual components broken out?

Good point. I should have qualified what I wrote previously by saying some CSS properties (like padding) could be simplified with just one way of writing the syntax. I say simplified (but not necessarily shortened) because it means you no longer need to explain that property x can be written this way. Or it can be written that way. Or it can also be written yet another way.

> I didn't think padding was inherited?

I forgot that padding required explicit "inherit".

So, bottom line, yes, it would seem to make sense to just have the single-line complete version:

  padding: *w* *x* *y* *z*

That doesn't matter, you had it right the first time and there is a still a reason and a need for being able to specify single elements of a property. Say, you set a specific font size and font family for the body, but want some element to have a slightly smaller font size... having to explicitly repeat all the stuff would make CSS unworkable. (look up the "font" short hand, there is quite a lot in there, and that's just one of so many, e.g. backgrounds and background images)

I'm referring specifically to padding; whether reduction of options is appropriate in other cases I didn't address. The balance if brevity, specificity, and distinct function (e.g., inheritance) is not the same for each of the cases where CSS has multiple forms with overlapping function.

"About how the only way to get two columns of equal height, but that expand to fit the text, is to use a <table>, but that this is supposedly disallowed because it's "unsemantic"."

This is incorrect. Using display: table and display: table-cell allows you to achieve equal height columns.

Well yes, if you make a div work like a table and a nested div work like a table cell, you can indeed technically get away without using tables and cells, but you're fooling nobody.

+1. In what world, other than the current one fraught with our bizarre legacy, would you link the concept of vertical centering with the concept of "tables" and "cells"? How about: "display:non-idiotic-mode" and "display:layout-support-any-sane-person-would-expect", and now you can use "vertical-align"? A bit verbose but more accurate!

Tables (or grids) are a very natural way of thinking about layout. Just about every webapp/site uses some sort of grid scheme as its layout model.

This is probably why the woefully layout-inadequate CSS had to include these hacks to mimic table behavior.

So, it's more like CSS is fooling nobody.

I've never really understood people who say CSS is horribly designed. In some ways, we are trying to apply desktop application design paradigms to something that started document or content oriented.

I can tell you that I'd much rather use CSS than Android XML layouts, or WPF, or adding layout containers a la Swing or AWT. It's simple, easily understood across disciplines, and very powerful. Elements of a pretty well designed system.

It's simple, easily understood across disciplines, and very powerful. Elements of a pretty well designed system.

On the other hand, it's 2013 and we're still trying to figure out how to center one element inside another.

In some ways, we are trying to apply desktop application design paradigms to something that started document or content oriented.

Which is exactly the problem. Web development today is a Turing tar pit, because we're using tools that were originally created for very different purposes. HTML is great for static documents, and lousy for apps. Javascript is great for attaching dynamic behavior to widgets, and lousy for large-scale software projects. CSS is great for consolidating style information, and lousy for layout. Yes, after over a decade of hacking by many smart people we've built up elaborate frameworks that sort of do what we want most of the time, but I wish we could have had more appropriate tools in the first place and been able to spend those resources elsewhere.

> On the other hand, it's 2013 and we're still trying to figure out how to center one element inside another.

100% this. CSS is a very powerful tool if you know its quirks very well, and there are a lot of quirks. I know a lot of incredibly talented developers who can pick up any programming language or technology in no time at all, but still occasionally waste half a day circle-jerking with CSS trying to make it do something incredibly simple like center one box in another or baseline-align a couple of pieces of text.

Agreed entirely that this is the problem today.

However we did have that (Java applets), and they didn't take off. I think the web did hit a bit of a sweet spot at the time, but it's time for us to build new technology on top of it. Personally, it's looking like asmjs, inline styles and translate3d divs to me :)

Documents, in the real world, are full of layout that has been difficult to replicate in CSS. And to counter your point more directly CGI and the concept of web applications existed before CSS 1.0, so there was already need for application-style layouts when CSS was being designed.

Flexbox isn't the answer either. I had high hopes for it and I'm in the middle of redesigning a web application UI using Flexbox for layout, and I still can't do some basic things like have an overflow:auto content area that expands to fill the space between a fixed left-hand nav panel, a variable-height fixed header, and a fixed footer. I'm still stuck with a bunch of javascript and a window.resize event handler to measure some heights and adjust the sizes of my containers. Maybe the upcoming CSS grids will work, but it'll be another couple of years before support is wide enough for me to use them.

EDIT: I also wanted to say that I've learned xaml in the past few years, and that's absolutely not the direction I'd want CSS to go.

i second this. CSS may be crap, but switching from frontend-development to swing-stuff makes me wanna hang myself after a few minutes. (And i worked with awt/swing/swt long before i touched CSS.)

Try qt/smoke if you can. An API that actually makes sense and just does what you expect - or you can use QML, which is what HTML for applications ought to look like.

Wpf is fantastic, it is everything html could ever wish to be.

I agree that it's a disaster, but: Is there any better language? I feel that very few of the "native" variants have APIs that are simpler to deal with. (Of course Sass is much better than vanilla CSS, but it's basically the same if you strip away the sugar)

XAML is very well designed, not for the web though. It was designed from the ground up to be consistent with only one implementation, as opposed to CSS, which evolved over the years on multiple implementations. It can get quite verbose since it's XML-based, but at least what you code is what you get.

I feel that CSS is pretty well designed. The problem is that it has so many ways to do the same thing, and the fact that vertical and horizontal layout don't work the same way.

I've not built apps in xaml but I've heard the that its a PITA once your app gets to a certain size and complexity.

I agree, I just think it's well designed and consistent. Plus, CSS can also be a royal PITA, that's why I take refuge in back-end development when possible.

Show me a presentation language that is as flexible and powerful as CSS. Try styling something in a native gui language, or something like xaml, and I guarantee there will be many more curse words.

A lot of people who are shocked with the complexity of CSS aren't saying this after switching from another better GUI environment, they're getting into visual apps after doing backed work.

CSS is not perfect but I'll take it over previous presentation idioms any day.

> Show me a presentation language that is as flexible and powerful as CSS. Try styling something in a native gui language, or something like xaml, and I guarantee there will be many more curse words.

You're on. I pick QML.

I must admit I'm unfamiliar, but at a quick glance it does look quite nice.

What are some examples of previous presentation idioms you're thinking of? I think I can relate to what you're saying, but I'm trying to think of concrete examples.

Cascading text styles are pretty well done, I think. The issue is entirely with box models, floating elements, scrollbars, positioning, z-index... you know. Everything to do with layout.

> Short answer: CSS is just a horribly, horribly, terribly badly designed language.

On the contrary, it's the box model that's horribly designed. CSS is quite excellent.

We're long past the days of web pages being simple hyperlinked documents, but the browser's layout options haven't evolved quickly enough.

Short answer: CSS is just a horribly, horribly, terribly badly designed language. It's the absolute worst.

16. When your language is nowhere near Turing-complete, syntactic sugar can be your friend.

My journey:

See this well trafficked "CSS sucks"-type article, Ctrl-F the comments for John Nagle, be tantalized at the hints of how it could be so much better: http://www.raizlabs.com/blog/2006/09/25/ten-reasons-why-css-...

Look up "constraint-based layout" and more specifically "constraint cascading style sheets". You'll find papers such as this one: http://citeseer.ist.psu.edu/viewdoc/summary?doi= and this one: http://csis.pace.edu/~marchese/CS835/Lec7/mmJournal.pdf thoroughly describing such a system.

Find "GSS - Grid Style Sheets" at http://gridstylesheets.org/ , "an implementation of Badros & Borning's Constraint Cascading Style Sheets". This is still half on my todo list, but it seems like the real thing. The catch? Relies on Javascript.

Dream of a world in which this kind of system was built into browsers as the primary way of doing layout <insert Simpsons happy dancing people gif here>.

Best comment in this thread IMO. Thanks! Some key parts from John Nagle's comments:

It’s not that CSS is hard; it’s that CSS is bad. (...) The worst problem with DIV-based layout is that the layout system is too weak. (...) There’s no way to relate a DIV to anything but its predecessor, its parent, or an absolute position. (...) Table layouts allow table cells which span multiple rows and columns. If all tables could do were simple grids of cells, the CSS approach might make sense, but tables are more general than that.

It's absolutely stupid and frustrating. Almost nothing in modern web design just works and it's because of both a badly written standard and badly written implementations.

I get it that HTML is supposed to be for content, CSS for layout and JS for programmatic logic, but the house of cards, duct tape, bailing wire and chewing gum that goes into making a web application is astonishing.

I almost think it would be easier for somebody to come up with an entirely different "web application/dynamic document layout" technology stack with a sane and well-working model all the way through, so that stupid basic things like vertical alignment don't go unfixed year after year after year and we end up with the teetering tower of hacks we have today. We pretty much know what we want out of the web, somebody should just go build it from top to bottom all over again and throw out the huge train wreck we have to deal with today. Sure it would take a while to catch on, but I bet a more efficient set of tools and display environments would rapidly catch on.

We've done it before and replaced older broken technologies with newer, why not do it again?

People compile languages with completely different ideologies to the JS object system, so why not compile a better layout model to the CSS box model. The CSS box model is going to be with web development, in it's current form, for at least another five years. So, why not use it as a compilation target.

I'm not sure that CSS is has the "Turing completeness" equivalent for layout that a programming language like Javascript has for computation.

That is to say, it's not possible to create any conceivable layout with CSS alone. It might be possible if the thing spits out Javascript as well.

You don't need turing completeness to be a compilation target, but you have the right idea with additional javascript. For a box-glue model, similar to Latex, you would have to make some adjustments when resizing. The generated code might end up similar to what twitter bootstrap does it, but one step more abstract.

> I almost think it would be easier for somebody to come up with an entirely different "web application/dynamic document layout" technology stack with a sane and well-working model all the way through, so that stupid basic things like vertical alignment don't go unfixed year after year after year and we end up with the teetering tower of hacks we have today.

Yes, but if someone managed to create a logical, concise Web publishing standard that was something other than a can of worms, it would be a proprietary system, most likely patented. Which means no one would voluntarily adopt it.

The advantage of a public, open-source, no-one-in-charge system like we have now is that it's collaborative, democratic, and free. That's also its disadvantage.

For a classic counterexample, look at Apple's products -- they create much more consistent and usable products than the rest of the marketplace. But as many have said, Apple is a walled garden. If an Apple product happens to do what you want with no changes, then fine, otherwise you're out of luck.

Freedom is messy. Democratic technology seems always to veer toward chaos.

It is not democratic. Democracies at least involve periodic check-ins with everyone who is affected.

The W3C isn't a town hall, it's more like the UN. At best they prevent the web from going back to the chaos of the mid-90s.

I wonder if this is a result of a broken committee process that should have had a benevolent dictator in charge of it instead.

> ... should have had a benevolent dictator in charge of it instead.

Like Guido Van Rossum in the Python world (with the title "Benevolent Dictator For Life"), who seems (so far) to manage his power well. But I think this is a rare exception to a well-known rule about arbitrary power.

Look at what happened with Dart. No-one's going to try writing a better replacement for a web technology in a hurry after that.

What happened with Dart? The only thing happening with Dart is progress.

> I almost think it would be easier for somebody to come up with an entirely different "web application/dynamic document layout" technology stack ...

It was called Flash. Or Java applets.

See history.

Purists will attack if you do this, but if you just want to get something done, using tables for layout often solves a lot of these headaches. Horizontal and vertical alignment of left, right, center, top, middle, bottom are quick and easy.

Edit: since you are a new developer, let me add that "ugly hackery" is what you quickly arrive at once you start doing anything of reasonable complexity (read: stuff that's actually useful). Handling the edge cases is what consumes most of the code in real production applications, and this is conveniently omitted from the beautifully clean code presented in tutorials and examples.

One of the problems is we often have people doing web design was if it's print design. Find yourself a focused web designer who really understands the medium and, chances are, you won't run into this sort of problem. A good web designer understands that different browsers are going to have different capabilities, and build graceful degradation into the design. A good web designer knows that screens come in all shapes and sizes, and will avoid raster graphics and px-units wherever possible.

CSS, from my experience, makes it very easy to do web design the right way and very hard to do it any other way. It's just that the right way is often a little different from what people expect. If you accept that <i>the browser is the boss</i>, you'll be a lot happier, and incidentally your users will be a lot happier as well. The trouble is people coming from other platforms or mediums often expect 100% control, and for that it really doesn't hold your hand.

"...the amount of hackery that goes into making webpages look the way web designers want them to is astounding."

I totally agree. For example, the CSS box model sounds so simple and elegant at first, but when you add dozens of styles and elements to your page, the interaction between different styles can quickly become horribly messy no matter how disciplined you are with your CSS code. Beyond a certain number of styles, CSS inheritance turns into a black art.

CSS simply doesn't scale well for anything beyond relatively simple pages. A huge part of designing web pages is layout and spacing and yet positioning and spacing elements remains ridiculously messy and convoluted (even with CSS3).

You could also argue that tools like SASS and LESS are in effect sticking-plasters for inadequacies in CSS.

I know hindsight is a wonderful thing, but if we were designing CSS today from scratch, I think it would be designed very differently.

CSS could be redeemable if; the box model defaulted to box-sizing: border-box;. If vertical-align and margin: auto (or variants) worked with variable heights and widths, and on all elements. If percentages of heights worked inside all elements.

It seems like flex-box fixes a lot of this, but at the same time, it could be so much easier.

You're right though. CSS would be so much different and so much more gloriously painless to use. I can even imagine a better styling engine allowing for applications like macaw, dreamweaver to actually generate properly good CSS and thus building sites with a GUI would finally be plausible.

We're working on solving these problems with new tools (flexbox in this particular case), but it takes time for those tools to become widely usable. You can look at e.g. Google's Polymer project for a glimpse at the vision for web programming in the future.

90% of webdesign is dealing with errant behaviour.

It's why it's so frustrating when people treat front-end design with disdain as something trivially easy. Of course, if you only decide to serve the newest version of Chrome and Safari, it can be easy to remember that there people out their who don't - or can't use them.

> webdesign

It's web development you're referring to.

Without wishing to descend too much into semantics the accepted definitions (at least within the industry) seem to be that "design" is basically Graphics/Layout (so includes HTML/CSS) and development is programming (either client or server side).

I don't agree. Design is design, development is split into front- and back-end specialisations. Some developers straddle both, but there are few people who are both (good) designers and developers. I don't know of anybody within the industry who would refer to a front-end developer as a "designer."

It depends if you are programming or simply describing page layout. Front end development could also include things like Javascript. There are plenty of designers who are not Javascript programmers but who can use CSS etc.

HTML and CSS are programming.

You could probably argue that in a technical sense but it's a person who works with HTML/CSS but not say JS etc would probably be considered a designer more than a programmer.

I've worked at a bunch of different companies (Yahoo!, The Guardian, various smaller companies) and in all of them the "designers" were the people who did the visual design using Photoshop and Illustrator - those people rarely if ever wrote HTML and CSS, and almost never to production level standards.

The people writing production-ready HTML and CSS were known as "web developers" or "client-side/front-end engineers".

Some would argue that whole doing the web with markup and stylesheets thing is completely wrong (Bret Victor comes to mind). And I tend to agree. CSS is a hack, heck, HTML itself is a hack.

Some material:



I'd love to know why just using tables is wrong.

The user gets what they want, the designer gets what they want, and the only people unhappy are some purists.

why? what about this is wrong?

I would have agreed with you maybe 2-3 years ago from a pragmatic standpoint, but the most compelling reason now for not using tables for layout is that they're not compatible with responsive web design. Table cells don't stack and can't be reconfigured like block-level elements.

You can get away with using "display: table-cell;" and the like inside components that are independent of responsive requirements, though.

Tables are for tabular data--designing with HTML/CSS isn't perfect, but using tables for layout is an even less-elegant solution. It leads to a markup soup of nested tags and tables and difficult-to-maintain codebase. Good design and good markup go hand-in-hand and often you need to strike a balance between flashy visual design and solid underlying structure. This is also why visual designers should understand how their designs get implemented in HTML and CSS--it will create a restraint and limit the amount of "hacks" you have to do to make a design work.

Also remember that not everyone views the web in a browser. Having well structured markup helps those that use screen readers or alternate methods of browsing the web.

"Good design and good markup go hand-in-hand"

I don't think this is true any more than "good print design and good postscript go hand-in-hand".

I don't think tables are the right way either, but they're too often the pragmatic way until CSS gets dramatically more expressive.

The "restraint" you're talking about is not something designers should have to accept —- not least because CSS appears to be being developed with insufficient concern for what designers would actually like to be able to do. If it wasn't, vertical alignment would have arrived long ago.

Table-based layouts will bite you down the road. Ever try to make a div that completely fills a td? Ever try absolute positioning in a table? It is tempting to use them because they are so simple and "just work", but they come with unforeseen consequences.

A key problem with table based design is accessibility: while table based designs aren't automatically a problem for screen readers and such, a great many are.

It also makes it far harder for other user agents to make the design fit in small spaces: many table based designs are completely unusable on mobile devices for instance. While the alternative might still not look nice in such an environment, it is more likely to not be completely impractical to use.

Of course if you are presenting something that naturally fits in a tabular structure, tables are the thing to use as that is what they are designed for.

Everyone who says using tables is wrong, is wrong. The only issue as far as I'm concerned is it is tedious to style tables, and you have to have <table><tr><td> all the time which is tedious to work with. All the other arguments are perfectionism. Even the accessibility argument is nonsense nowadays, it amazes me people are claiming screen-readers haven't advanced in 10 years. TEN YEARS AGO screen readers sucked with tables.

Because tables were not made for layout. They were made to present data in tabular form, and it's still perfectly acceptable to use table tags to show data. But using tables for layout is like chaining a bunch of cars to make a makeshift train, both can be used to travel, but a train was made to move a large number of people, and cars can only move small number of people. There are better tools available. That and tables result in some very ugly code structures. And see the upcoming flexbox model. I have tried it and it really feels more apt, a lot better than using floats and a hell of a lot better than tables when it comes to satisfying, good and perfectly predictable symmetric code.

Actually, the original W3C proposal for tables specifically mentioned using them for layout. I can't find a working link, but there's also a RFC:

The HTML table model has evolved from studies of existing SGML tables models, the treatment of tables in common word processing packages, and looking at a wide range of tabular layout in magazines, books and other paper-based documents.[1]

It was only later when table layouts began to be discouraged.

[1] http://community.roxen.com/developers/idocs/rfc/rfc1942.html

I'm no purist but I am in the mindset, "you wouldn't use a fork to eat soup".

I do agree though that it is a pain when something is easily achievable in tables but doesn't work in normal CSS. Vertical alignment being one of them.

What does annoy me is when you see people creating "CSS table" systems. I'm not being funny but that is just plain stupid. I saw a whole project dedicated to replicating the behaviour of a table.

I started developing when tables were fine to use for all layouts and I feel CSS was adopted as a layout too early without some very basic things being answered.

If it solves your problem there is nothing wrong with it. However, tables are considered problematic because they encode the layout of the page in the HTML. Ideally, you would semantically structure your page using HTML and add style and layout using CSS. This way of working would allow for maximum flexibility - you can restyle your page without ever touching the HTML. If you use tables it becomes much more difficult because the table already adds a certain fixed layout.

Unfortunately the real world hardly ever works like this.

I think people have gone too far with this mindset. I develop pages using a mostly semantically structured approach, but I'm not afraid to sprinkle layout-only elements where they make sense, especially when using grids.

On a purely practical level, using tables for layout makes it much harder to implement a responsive design where elements are arranged differently at smaller screen sizes.

> ...the only people unhappy are some purists.

Right. Purists like blind people who access your site with a reader, and Google's page crawler.

Google is the first one using tables for layout, since they started until today.

Google (Search) hasn't used tables for layout since 2007.

How Google displays their own search results (tables or divs) is irrelevant to how their crawler interprets everyone else's pages.

Just wondering. Why did you decided to become a web developer after so many years?

Usually developers try to find a way to solve the problem because they are engineers and that is what engineers should do. HTML, CSS and JS wasn't invented to what it has become today. It has evolved thanks to people like you and me who has find ways to use to our advantage. Example AJAX was existed since dark ages (IE5+) but no one used/knew about it. Google used that in google maps in 2004. Now, pirates are using it in usenet/torrent applications (utorrent, sabnzbd, sickbeard etc), or 3d rendering in the cloud (http://home.lagoa.com/).

If you are waiting for something better to be found, i think you will have to wait long time. There is nothing on horizon that is as simple as HTML.

For me, hardest part is in the web development is to deal with designers and product managers.

I'm not a web developer. I just wanted to add a bit of web development skills to my set of abilities so I've been learning the Django framework and the nuances of HTML/CSS/JS.

We sorta had that already. It was called Flash (or Silverlight, etc. pick your poison) and while it was easier for authors to do many things, it sucked for users in more ways than I can count.


And no longer have to support IE7 (if you're lucky).

Be glad you did not have to do this when IE5/6 was still around and Firefox was starting to go strong. Sites with sole purpose todocument all the hacks you need to do to force IE to behave a still around.

Just in case anyone's unaware... it's entirely possible to vertically center elements of variable height too in pure CSS... it's just "unsemantic", because it relies on the fact that only table cells have "vertical-align:middle".

But that's how I center every one of my "modal dialogs" on a site -- the whole modal dialog is inside a <table> with position:fixed and top/bottom/left/right:0. Then, just give the <td> a "vertical-align:middle", and then put your desired visible dialog <div> inside it.

It's annoying to have to wrap something inside of a <table><tr><td> just to vertically center something, but it sure beats using JavaScript to do it. (You might be able to do it just with the display:table-cell property too, but it's been a long time since I checked browser compatibility.)

  > It's annoying to have to wrap something inside of a
  > <table><tr><td> just to vertically center something
And you dont have to. Because your container does not have to be a table, and you don't need cells and rows. Just use display: (table|table-cell). See for an example: http://css-tricks.com/centering-in-the-unknown/

It is not OK to use table and friends in you HTML just for styling purposes. It's totally OK to use display: table* in your CSS, because CSS has no semantics, its purpose is styling.

Why is it not okay to use tables for styling purposes? Why is it okay to use multiple nested divs, but not the table/tr/td tags? Are there any practical reasons, besides the goal of making the markup more 'semantic'? Are there any screen readers that can't handle table tags? Or do some crawlers choke on tables?

I keep hearing this dogma, don't use tables for layout, but nobody has ever explained to me why it is a problem in practice.

Being "semantic" (your quotes) is not an abstract concept or dogma. This discussion has been exhausted as far back as 2005. A more practical explanation:

HTML is meant to be parsed and interpreted by machines too, with no visual representation. Tags are meta-data about their content. A 'table' element says "I contain tabular data", and user agents will make lots of assumptions based on that. One of the consequences of this is you'll be giving bad data to search engine bots, that's why it's bad for SEO.

HTML is also meant to be used by non-visual interpreters, like screen readers. Assistive technology is not only for the legally blind; visual impairment affects 20-30% of the world's population. We don't see high user %s because they just most won't bother, it's too hard, sites' HTML is broken, it is easier to have somebody look it up for you.

Going on a little more over semantics, there are rules for what elements can contain each other, so that a structure can be inferred based on headings and hierarchy. By not following the rules you are wreaking havoc on this, and preventing aforementioned bots and screen readers from providing meaningful navigation and context for your page.

We were supposed to have a semantic web by now, where every piece of information was annotated with meaningful meta-data, allowing for context-aware applications (add this commenter on facebook; where can I buy this product?; add this event to my calendar). Turns out it's damn hard to get everyone to use markup correctly, or even agree to common formats.

> Being "semantic" (your quotes) is not an abstract concept or dogma. This discussion has been exhausted as far back as 2005

No it really wasn't. A small group of people managed to make it orthodoxy and in the intervening years very few of the supposed benefits have materialised.

In the meantime the same arguments that it is pie-in-the-sky have persisted and events have supported them.

The argument isn't even internally consistent as in the real world people are debating one kind of tag soup vs another. If the only way to create a particular appearance is either using several wrapper divs or a table then you're splitting hairs.

<div><div><div></div></div></div> vs <table><tr><td></td></tr></table>

Is that a semantic difference worth fighting for?

The real gains in the semantic web have come from small targeted blocks of metadata and natural language processing. Not waiting around for everyone to figure out <section> vs <article> correctly.

<clarification> I'm not arguing against the benefits of semantic markup - just that a lot of the hand-wavey "this is semantic and this isn't" advice that gets thrown around is either nonsense or adds such a microscopic amount of semantic information that it's not actually providing any benefit to anyone. The real test is to list actual benefits for actual user agents.</clarification>

Tables have a well(ish) defined semantics that you're breaking. Those semantics give rise to real practice benefits like navigating via column and row with screen readers or hinting how best to split a table up into multiple pages when printing.

Practically, the way it's ended up, the semantics of a div is "some stuff". It's evolved into the go-to method to hide a multitude of styling sins. I don't think there's anything hugely hypocritical in limiting any ugly semanticless hacks to a single generic container like divs.

Put as much as you can into semantic markup, and then anything else you really can't fit into that, favour using div soup over breaking the semantics of another tag.

What about inline elements inside divs? Even the semantic correctness crusaders freely resort to abuse of <b> and <i>.

HTML lacks extensibility. If you want to move beyond classical typography you have to make heinous compromises, and there is no reason <table> should be specially exempt.

I agree we have to make compromises because HTML has huge shortcomings. My point, and the point of a lot of people advocating semantic markup, is that if you have to resort to hacks, prefer lots of uly generic containers like divs and spans to misusing things that have better defined semantics that are actually of use to people, like tables. I can't think of anything you can do with tables that you can't do with an ugly mess of divs and a little compromise in cross-browser consistency.

Amen! For example, what is the practical advantage of using <footer>, <aside>, <artice>, <section>, today? I only ever hear "search engines or screen readers can/could do X", that but nothing about what any user agents or bots actually do. No examples, and no way for me to detect any difference it would make anywhere (other than having to include HTML5 shims for IE). That doesn't do a lot to get me interested in paying attention to that stuff, to move beyond "does it look how I want it to". In short, don't tell me what I should do for the robots, tell me what the robots are doing for me (or other people), with that stuff.

There are plenty of examples, articles, tutorials, videos, presentations on that topic (many linked here in this thread). You won't find what you're not looking for.

"on that topic", or answering the very specific question I asked?

If using tables for layout broke non-screen user agents (like screen readers and Google), then the web must have been more or less unusable by them until at least 2005. We know that's not true for Google, at least, and by 1999, Lynx actually had some capability for dealing with them.

Even if layout tables did present a problem, an easy incremental fix convention (say, `<table class="layout">`) might have been a nice addition to user agents for situations where people either hadn't invested in semantic markup + CSS yet ... or for the layouts beyond CSS capabilities.

That isn't to say that I think everybody should be using tables for layout or CSS completely sucks or we'd all be better off if we were doing layout like the Java/C#/Flash/Python library of your choice does it.

I'm just not sure the "tables break things" argument is particularly strong.

Yes, using a screen readers with a table-based website has always been a nightmare. Google invested heavily on research to be able to make sense of tag soup, that's one of the reasons it could provide way better results than anyone else. It's an ugly workaround, like printing a document and scanning it back instead of copying a file. See rest of discussion above.

> Yes, using a screen readers with a table-based website has always been a nightmare.

Have you experienced this personally, or do you have this on first-hand account, or are you repeating the common wisdom?

Because like I said, Lynx had a way of doing this circa 1999. It mostly ignored tables except a few that met some criteria for likely semantics. So you generally got a cell-ordered page, which worked surprisingly well for most sites. Heck, if you've got a copy of Lynx at hand, fire it up right now and browse HN (which is layed out via table, ridiculous though it is for a site with such a simple layout).

If Lynx can do it, I have trouble believing that deliberately assistive software wouldn't be able to. This matches most of the (admittedly limited) discussion I've had with people who use/write it (an aside: I've also heard that, believe it or not frames were sometimes a big boost to assisted usability).

If you've got personal experience or first-hand accounts, though, I'm interested to hear it.

I used to work at a company specialized in front-end development, where we used NVDA, Voiceover, Window-Eyes and Jaws extensively while building and testing websites, sometimes for legal compliance.

Lynx is a text-mode browser, not a screen reader; it's still visual. Assistive tech has a whole lot more going on. They have a slew of navigation modes and need cues from content to prevent the user from getting lost, you can't just scroll or look back up to where you where. I recommend looking at the resources below, and trying to use an iPhone or mac with voiceover and screen curtain enabled to really experience what it is like.

http://alistairduggin.co.uk/blog/screenreader-resources/ (collection of videos & articles)




http://www.youtube.com/watch?v=vK1tlLOavvM (linked by PavlovsCat below)

> Lynx is a text-mode browser, not a screen reader; it's still visual.

Sure. The point isn't that Lynx is an assistive UA, the point is that it's at least one UA that figured out how to throw away layout-purposed table markup (which, like some assistive UAs, doesn't make any sense in its rendering context) and still render (some) markup that represented tabular data.

Is it really the only one?

> Assistive tech has a whole lot more going on. They have a slew of navigation modes and need cues from content to prevent the user from getting lost, you can't just scroll or look back up to where you where

Right, but is that really tied up with non-semantic table use? I'd think it's the presence or absence of things like access keys, title/alt text, and I guess at this point aria attributes that makes the difference, not table markup.

Exactly, Lynx is not an assistive UA. Keyword there is `render`. It makes very little use of tags' semantic meaning compared to a screen reader. Alt/title attributes are just a small part of the picture.

You are underestimating the damage bad markup does, and how deeply assistive software relies on semantics/metadata/structure. As I said, just fire up voiceover and try to browser HN. Actually, I'll quickly do that for you:


I'm comparing table-based HN to one of it's alternative interfaces, not ideal but much better. It's a very shallow example, and I'm using only basic navigation commands - experienced users can use more complicated navigation schemes to discover content, out of necessity - but you get the idea. Lots of noise (row x of x, column xxx..), blank cells are "read", etc. Remember HN is a very simple and spartan website, now imagine what a slightly more complex nested table layout looks like.

Also, see WebAIM surveys for actual assistive tech usage data: http://webaim.org/projects/

> Lynx is not an assistive UA. Keyword there is `render`. It makes very little use of tags' semantic meaning compared to a screen reader.

It is, however, apparently smarter about the use-semantics of table markup than most screen readers, if I'm to take your example as the norm.

> imagine what a slightly more complex nested table layout looks like.

Having spent more time than I care to remember inside the code of complex nested table layouts, I unfortunately don't really have to work too hard to imagine. :/

> You are underestimating the damage bad markup does, and how deeply assistive software relies on semantics/metadata/structure.

I can see/hear from your example that the table markup is a challenge for voiceover.

I'm not sure I was underestimating the damage repurposed markup does more than I was overestimating the ambitions of assistive UI devs. I'm just astounded that voiceover wouldn't haven't implemented at least a mode for making likely distinctions between table markup that's being used for tabular data and table markup that's being used for layout, when making such a distinction is not only clearly possible but has been done.

Then again, I'm astounded that it's 2013 and Adobe still can't install onto case-sensitive volumes, so there's that.

ARIA provides a solution for the problems caused by <table>.

If I remember correctly, the summary="", was suggested for layout tables. I never looked into screen reader support for that though.

That's smart. A present but blank summary attribute would've been a great indicator.

I also think that it could've been done pretty reliably by heuristics. A table that mostly has data cells that contain lots of images or block-level markup as descendants is quite likely a markup table. A table that has mostly text or inline-marked cells and has a full summary attribute or <caption> is all but certainly semantic.

I guess with IE 6&7 all but dead, though, it's sortof irrelevant now -- you can mostly count on `display: table-cell` to help you out of a jam.

What you want to make (modern) screen readers not try and parse the table semantics is to set the role to presentation:

<table role="presentation">

"Turns out it's damn hard to get everyone to use markup correctly, or even agree to common formats" - perhaps because it's damn hard (read: often impossible) to get the intended visual presentation for the majority audience of sighted users to look right without resorting to non-semantic markup.

I've pretty much abandoned many sites' designated markup for either 1) Readability's version or 2) my own CSS using Stylebot. It's relatively easy to make significant corrections quickly, and for sites I spend significant time on (say, G+, HN) it's downright useful.

Some examples from an earlier post:

Hacker News itself: http://stylebot.me/styles/2945 Buzzfeed was particularly fun: https://plus.google.com/104092656004159577193/posts/G6pzJBLK.... NY Times and Edge Perspectives: https://plus.google.com/104092656004159577193/posts/NUMQuQUh.... Basically: if it moves, is fixed, is an interstitial, or is just plain annoying, I kill the hell out of it. And with Stylebot, the easy stuff is just point, click, and "Hide". Then it's gone. Bring it on.

The guy who first thought of using tables for layout lamented this back in 1997 in "The Web is Ruined and I Ruined It": http://www.xml.com/pub/a/w3j/s1.people.html

I have the exact same issue. I find it much less semantic as well as less readable and maintainable to use abstract markup (i.e. div) everywhere.

<div id="rant"> Presumably the goal is to create a strong separation between layout/design and content as HTML is want to do. However, I don't agree with the premise that design is not content even in the context of translating 'content' to different display systems including for the visually impaired. A movie cannot be automatically retargeted to a blind person by just playing the audio, you must actually do the work translating it to a different form such as a novel, or scene descriptions read aloud. Sometimes as with say a Woody Allen film, you wouldn't miss much if you could only hear it, but something like 2001 wouldn't work so well. Like it or not the internet works exactly the same way, all 'content' does.

Layout and design is content. </div>

It's not the exact same issue, it's the exact opposite. Using meaningful markup (not div) where it shouldn't exist is more harmful than the contrary. Not using tables for layout doesn't mean you can't use tables at all - use tables for tabular data.

Ask a blind person how they feel about you not agreeing that they should have access to the same web you do. They actually do 'watch' movies and TV by audio only. A lot of information is lost, but it's better than nothing. And with a web page using correct markup, a good screen reader interface, and some practice, they can navigate and consume information much faster than we can visually.

with a web page using correct markup, a good screen reader interface, and some practice, they can navigate and consume information much faster than we can visually.

http://www.youtube.com/watch?v=vK1tlLOavvM <-- Léonie Watson, "Design like you give a damn: Practical accessibility for Web Pros" = very good talk, crucial crash course, and includes a great demonstration of the bit of your post I quoted :D

Bingo! This

Great talk!

Slight left turn on the topic, but I think people can lose some elasticity in their thinking when they try to be politically correct. Accessibility implies impairment, but that can give you a mental model of "blind people are people too so we should be careful not to exclude them". But that's bottom up thinking you should be thinking what is possible, or top down thinking.

The mental model is completely different if you take political correctness out of the equation. What if we are talking about a person driving a car using a web interface? Now the user can't see because of a situational limitation not a physical one. There is no need for the implication of sympathy.

It's inspiring to me to design for any IO method I can think of. Aiding accessibility is useful to everyone, but I call that user experience and usability. This is why I get bent on some of the thinking behind HTML. Design, to me, isn't a second class citizen when communicating with your user/audience. New devices show the same information but did we just use the same html and css no we reformatted for the devices. What about when we are all using google glass and web enabled watches?

Granted many web pages that where redesigned for 'mobile' would have done better to leave well enough alone, but that's just bad design.

I think we are agreeing, and I don't mean to spin up the same debates. I'm just saying that as it is html presumes that the important content is the text and throws everything else over the fence. It implies that you are done with translating for all displays if you just follow proper html best practices, when in fact you should consider targeting your content for specific displays in many cases.

I absolutely did not say that a blind person should not have access to the web I said the opposite, a designer should be mindful of their various audiences and design for them purposefully and not expect that a file format can do that for them.

I wish there where layout oriented and data oriented table tags, but there isn't so table gets used for both if you want anyone looking at the code to to get what you're doing. I also wish you could designate where the 'content' actually is sometimes its the text sometimes its the imagery sometimes its the layout. Then at least you'd be clear on where manual translation is required.

The problem with that is that 99% of designers (or their boss) would not consider screen reader users as their audience. Designing purposefully for the visually impaired means using semantic markup, ARIA if needed, and being careful to offer annotations where content is mainly visual. Creating a separate experience would mean duplicating your whole site, and nobody would do it because of the cost - or even worse, create a limited, reduced version, like the mobile-specific sites with all their problems we all hate.

It's a hard issue, but the goal of assistive technology is to include people with disability, not segregate. If you want to create a specialized version for them, by all means go ahead, but HTML and ARIA were designed with this goal in mind. I don't think there is a better tool for this.

> I wish there where layout oriented and data oriented table tags [...] I also wish you could designate where the 'content' actually is

That's where `display: table` comes in. New elements in HTML5 allow you to designate content, supporting text, images, navigation areas: main, article, nav, figure, aside, etc. This could already be done with ARIA "role" attributes in HTML4/XHTML.

It's gotten to such a weird point, though, that when I had data like this:

    [icon] item name    item date     [command]  [command 2]
    [icon] item name    item date     [command]  [command 2]
many web designers told me to use unordered list items! Yes. Ok -- um two questions

1) Why is it called "unordered" when there is still an order? Bad naming ...

2) More importantly, how is the above not tabular data? Who becomes the arbiter of what is tabular, then, if the above is not tabular?

It could be tabular data, but it depends on context. If this was an order list, for example:

    Napkins     21-07-2011 14:52    Change  Remove
    Pitchforks  21-07-2011 14:52    Change  Remove
It's not necessarily tabular data, you only have two columns. It could be represented differently without any loss:

    | Napkins       (21/07) |
    |                       |
    | +--------+ +--------+ |
    | | Change | | Delete | |
    | +--------+ +--------+ |
    + ----------------------+
But if you had more data columns and headers it'd probably make sense to use a table. It's about providing meaningful context, relations and hierarchy, there are no hard rules.

Unordered lists mean the order they have is not meaningful. It's physically impossible for something not to have an order...

The essential reason non-tabular data shouldn't be represented as a table is because HTML tables coerce a particular presentation, whereas you can use CSS to arrange data in a tabular presentation if you want, or if you want to do it differently, just use a different set of CSS.

The whole concept of tabular data is a concession to people who insist that they have to use tables.

it's called unordered because the "ordered" list <OL></OL> adds numbers beside the items.

I used to hear that dogma too. And then all of a sudden I'm reading everywhere that I should check out bootstrap.css, which flies straight in the face of semantic markup by requiring you to use class names that are descriptive of their layout effect. I don't know if there is overlap between the evangalizers of semantic markup and bootstrap.css, but if so, it would seem contradictory.

I used to be against class names that are descriptive of their layout effect, but honestly, it's the simplest way a lot of the time. You can't always think up the exact right name for a random element somewhere on a site, and getting into the habit of using sane oocss can save a bunch of time.

Classes and IDs have no semantic purpose in HTML[1]. Bootstrap's approach is bad from a developer's perspective, but is not bad as long as you use the right elements.

[1] search/indexing bots do look at classes to try to make sense of a page, but only because of tag soup and the lack of structural elements before html5

The CSS "display: table" and "display: table-cell" are designed to act exactly like their html counterparts.

If you are trying to provide a layout for both mobile and the desktop, putting tables in your html will definitely make it harder. If they are in the CSS, you can use two different CSS styles for mobile and desktop.

Just a small example, as I didn't see it mentioned in other replies.

Often when I write stylesheets for a site, I like to have a default table style. Type, possibly border/spacing, padding, etc, depending on the site. Even if there are multiple visual "types" of tables to display, typically they will all have a common set of margin/padding at the least.

If you wanted to use a table for layout in a site with default table styles, you would have to have a whole set of style resets to get it back to zero layout, before adding your custom layout stuff. This is ugly, and a pain.

One point of using a div for layout style is that it is always "zeroed", and you can assume when styling one that there's nothing that needs to be overriden.

Thanks for this, but of course the question got closed.

I don't see the problem: there's a question, there's a good answer, so it's closed. Not everything has to be an on-going debate.

That's not what happened. There's a question, it isn't the sort of question the stack overflow wants to have, so it's closed.

For a change it's actually a close decision that was a good one.

While I agree it's better to avoid tables for styling, I see why people resort to it as it is much simpler.

I love how your example uses 'something-semantic' as the class of the nested divs, as if labelling them semantic makes it so - this is an ugly hack around a deficiency of CSS and not far removed from using tables. It is possible to centre things vertically (with nested divs) or have several columns of freely defined height, but people have to go to extreme lengths to do so and mangle their markup in the process, because CSS is sorely lacking in some fundamental aspects of design. Things which should be simple are hard, and it's impossible to truly divorce the meaning from the form because of bugs and deficiencies in CSS, which leaves us adding nested divs all over the place to get the correct layout.

CSS should have had vertical and horizontal centring for blocks from the start, it should also have had some system of grids and columns and a concept of baselines. It's painfully clear in the design of CSS and the huge gaps in the coverage that it was an ad-hoc reaction to browser developers' problems, not to the problems of designers styling HTML. It could be radically simpler and have far more power if they went back and rethought the foundations of the box model and considered other techniques like grids which have been used for hundreds of years to present information.

Thanks for that link, it is very enlightening. So much of CSS just feels like a total hack. putting something in the middle of an element should not be so hard! negative margins? ...absurd!

Why doesnt CSS just have a property like 'placement: center middle' or something.

CSS is the epitome of design by committee, only worse. It’s worse because some members had a vested interest for the standard to fail. As a result, we get threads like this from designers, and programmers; they're in a worse bind. It’s just not possible to efficiently hardware accelerate CSS.

Of JS/DOM/CSS in HTML5, CSS is the worst standard. Depreciation is the best we can hope for. I’m sure MS and Mozilla will fight it tooth and nail, but maybe Google will pull a Dart/Go here and give us something decent to work with.

I've got exactly the opposite opinion: of JS/HTML/CSS, CSS is y far the best standard.

People complain because it doesn't address their specific needs explicitly (e.g. vertical centering) - but that way lies madness; a huge spec that caters for every case explictly, and probably has lots of corner cases and interactions meaning that cross-browser support would be even harder than now.

CSS is limited - and that's a good thing. Would you want to implement complex layout in JS, say? And how that would look when window size changes, or the page is zoomed, or some font isn't available?

The declarative nature of CSS is what makes it work; and the key aspect of declarative here is that it represents a state, not an algorithm - it's not turing complete. You'll never be able to do everything in CSS; and that's by design.

It's not an issue of turning completeness. CSS was never designed to be hardware accelerated. So many implementations run faster in software. Here's a good example:


CSS is thought out for it to be possible to implement a fast layout engine. This requires a few concessions. One concession is that it (mostly) requires that layout defined by a partial document is the same when the document is complete (to allow for documents to be laid out on the screen as they come in from the slow network).

A placement: middle, without a rigidly defined height, would require the layout engine to know about document information after the element requesting a middle placement.

People complaining about CSS usually complain about the illogic of cascading, which I don't understand. This, however, captures the weaknesses of CSS a lot better. CSS is strong when it comes to styling text, but weak when it comes to doing layout.

It would be nice to see a complete overhaul of how presentation is done, with what people have sought to do on today's web in mind.

That's what flexbox does, mentioned at the end of the post, it just doesn't have enough support yet.

Does flexbox support the centering of elements like the canvas and a webgl context? Does it offer facilities for resizing either of these elements? If not, is there anything out there that allows for resizing these elements with the rest of the page?

Yes, you can use percentage units.

I'm surprised nobody has mentioned the display:inline-block approach to vertical centering. It's a bit awkward for a couple reasons but it is responsive to dynamic content (no fixed dimensions are required), and it does not require tables. It does require a non-semantic (albeit empty) "shim" div. I'm not sure how well it fares in Ye Olde IE 6.0 but hopefully this is not a concern to most webdevs today.

Here's a jsfiddle to illustrate it. http://jsfiddle.net/qu5jq/

At least in every browser I've tested, display:table-cell works, as long as that is inside another element with display:table. This allows one to retain pedantic purism of all divs.

It's not as big a deal anymore, but table-cell is not supported in IE6-7.


>not a big deal

Browser still has more users than Firefox had some years ago when we started talking about supporting all browsers. Unfortunately.

According to stats, only 0.8% of users are using IE6-7. Is there any logical reason to spend quite a lot of time to adjust your css to work properly for 0.8% of your users? And if you are building a premium product - I don't really think this 0.8% are the one who are going to purchase it...

You should look at your own stats to decide that. IE7 accounts for 4% of our users, so we do make some concessions for them.

around 2% here... but by far some of the best paying ones (corporates).

wow, that's just.... painful.

Why the heck would a company stick to IE7? It's not like the compatibility modes of later IE's don't work or something...

in this particular case, the company is global and has a fixed load set for their computers/notebooks. the last version was compiled together around 5 years ago.

when you have to support multiple thousands employees, having a stable environment is key. upgrading becomes an expensive and slow process.

the next load set at that company is currently in testing for the last 9 months (!) and will upgrade to ie9 and office 2010 - both will be around for a few years to come, their extended support periods end in 2020.

Inability to work out how to deploy later versions of IE and push out compatibility view lists using group policy (I'm no windows networking expert but this has to be possible right?)

It's funny how so many web devs just ignore older browsers out of a sense of superiority towards users of those browsers. I've even heard some of these guys say "they're not my target audience, so why should I care?" They are, of course, inevitably, Apple fanbois. Fortunately, they are not usually in charge of making business decisions at any significant companies.

I'm ignoring older browser because it's the difference between a lot of pain and a modicum of joy. (Also, most of the actually cool stuff these days? "Sorry, must be this modern to ride")

Also, if you keep supporting older browser, people will keep using them. If they keep using them, they will likely have vulnerabilities. So in a sense, dropping support for old browsers is like tough love.. it's not an easy choice for anyone to lose out on however small a fraction of visitors/users, but sometimes you just have to do it, "for the greater good".

I just woke up from a nap in 2009. I hope. Gonna go invent chatroulette now.

Is it considered ignoring them if I go down to the shooting range, put the IE6 logo on the target, and let loose on a weekly basis?

Its funny how many people spend so much time supporting old browsers out of a sense of superiority towards web devs who ignore them. I've even heard some of these guys call us "Apple fanbois".

using translate() you can center variable width/height stuff too (without the table stuff): http://css-tricks.com/centering-percentage-widthheight-eleme...

Wow, that's awesome. As soon as I get to drop IE8 support, I'll think about using that.

I had no idea you could use % within transforms that referred to the size of the element itself (since all other % in CSS refer to the size of a parent element).


display: table-cell is my preferred method and it's supported by IE8 and up.

...like you said...all that cruft...

It confuses me that you have to specify things in terms of margins, I understand how that is technically correct but surely something like alignment: center should just align to the center of the parent element?

I've spent hours in the past the past getting correct centring behaviour in CSS, then tried by just putting the whole thing inside <center></center> and had it work immediately in all browsers. But apparently that's "cheating".

Cheating according to who? Surely not your website's users?

It's the standards makers' fault. Needing to center something on either the x or y axis relative to the parent is as common a scenario as you can get.

Well technically the center tag is deprecated so any browser could simply drop support for it (as they did with <blink> in a future version and break the site.

OMG, just use a table! It's not semantic but no one will die and your mom will still love you, I promise! And if you are using haml/jade/handlebars whatever it is so insanely easy to create a little mixin or whatever to keep your code clean.

Articles about how to do this should be summarized like this: "Vertical centering hard/hacky/messy unless you just put it in a table. So put it in a table".

(I do realize the article says this).

BTW, regarding the argument about the damage of using tables wrt screen readers, google themselves used tables to layout very basic buttons on their landing page until very recently. If you use it sparingly and just for this purpose, screen readers will do just fine. Now, using tables for other types of layout can and will break screen readers but a full old-school table-based layout is a long way from having a single TD to center stuff.

I haven't done any front end web work so I'm confused by this. Can someone please explain why it is noteworthy? It seems strange to me that something as simple as centring a box should require special attention. Why aren't such tasks trivial beginner stuff?

Centering content of unknown dimensions (and since the user is ultimately in control of font size this happens often) vertically is surpringly difficult to do if you want to support legacy browsers. It's a common pain point. There are others, but this one is particularly vexing (esp. to newcomers to CSS) because it seems, at first glance, like it should be easy.

Can someone paste the code somewhere else please? The linked website is broken. And yes, I have Javascript enabled. But it's probably using localStorage (with no graceful degradation), which I won't allow. Is this becoming a thing? Either you give up your privacy, or you can't surf the web anymore?

  margin: auto;
  position: absolute;
  top: 0; left: 0; bottom: 0; right: 0;
The JavaScript console error I see is:

  Blocked a frame with origin "http://s.codepen.io"
  from accessing a frame with origin "http://codepen.io".
  Protocols, domains, and ports must match.
localStorage.keys is null, thus the page does not appear to be using localStorage.

How is localStorage a significant privacy concern? My understanding is that websites only have access to the keys stored by that particular domain.

When CSS reached a certain point, using tables for layout suddenly became evil. CSS was like some strange measure of your salt as a frontend dev. Very Emperor's New Clothes type stuff.

But, I can remember trying projects with tableless design at that point, and absolutely beating my head against a brick wall attempting things in CSS that required almost zero thought with tables. Then, I'd finally get it right in one browser only to find that it looked like garbage in another.

It was like having a toolbox with a hammer that I couldn't use, instead being forced to nail everything with a screwdriver. And it wasn't just that I was accustomed to tables. They were easier and more natural. When you think about it, layout is nearly always grid-like.

So, I confess that there were times when I said screw it and reverted to tables. I'd solve problems that weren't working after hours of trying with CSS in literally minutes.

And the challenge with CSS is still apparent. Here we are all of these years later, still trying to do something as simple and frequently necessary as center things vertically which, BTW, doesn't work in my stock Android browser.

CSS is a bloated, convoluted mess and just too much work for simple things. That's why I have always found it somewhat draconian that people insisted on CSS as if it didn't have its own significant issues. If there were a tag that operated just like tables, but indicated layout or, as I think someone else suggested, a simple attribute to mark a table as layout vs row/column data, most of the semantic/SEO problems could be solved.

For that matter, I am not convinced that we should be so bent on having html pull double duty as the source for semantic data and the source for a presentation engine's rendering. Maybe a different approach altogether could be more liberating and efficient on both fronts.

Though I agree in some respects, I've been a convert of CSS since the beginning. My reason, floats for wrapping elements depending on screen size. You can't do that with a table.

>floats for wrapping elements depending on screen size

Not sure exactly what you mean here. Are you talking about floating divs to wrap elements to the next visual "row" for smaller screen sizes, as in responsive design?

Because I don't find this necessary very often in practice, and certainly not nearly as often as the tons of other general layout that's required. Not to mention, of course, that you can still use divs where "needed".

BTW, on a side note, the jury is still out on responsive design for me. Or, at least as I have frequently seen it practiced today. For instance, many times a site with sidebars (including nav) will wrap the sidebars on smaller displays such that content, nav, etc. are all lined up in one vertical column. Not very appealing or usable IMO.

I really believe that how we treat designing to different formats will change and this responsive wave will pass. And, while I know there are other reasons to wrap elements, I do think responsive design is responsible for a good bit of it.

People still use floats to make the sidebars stack up on narrow browsers? I thought they mostly went back to tables years ago.

I think it's still very common. In fact, tableless design is still very much the mantra from what I see.

But, you're right: tables can be used for the same.

Not something I've done much either way. I just don't think its a nice effect. Guess it's just a style preference.

Does it seem a bit off to anyone else in chrome?


Or is the browser chrome considered usable real estate.

You are correct, it is off by the height of the bar at the bottom of the window. It uses fixed positioning -- not absolute positioning as was prescribed in the hack. Also he sets the modal height to 50%. The CSS of the demo is not the CSS of the write-up.

This !!!!

You can also do this

position: relative; margin-top: 50%; transform: translateY(-50%);

You can, if you don't mind it breaking in IE < 9.

Looks good to me...

Why is such basic css hyped so much? Can someone technically explain it? Is the ratio of HN folks that need Web 101 greater than the ratio of people who need Startup advice, including technical and architecture solutions? (Been doing dev+webdev for >13y)

This article isn't basic css, it's a discovery of a simpler way to do a somewhat common layout task.

But overall your point is fair: HN has a lot of people (including me) with weak front-end skills.

It's not a new discovery. I've been using this for over a year...

Thank you, that was what I wanted to know.

The fact that something so simple needs to be explained as "a thing" or "a trick", many years after HTML5 even came out, feels like a disgusting frontend failure.

Pretty nifty trick, but I think undoubtedly the best is the transform 2D method detailed in this CSS-Tricks article: http://css-tricks.com/centering-percentage-widthheight-eleme... — You don't need to know the height or the width, and the great thing is transform2d's are supported in most browsers that matter. If you're smart and have dropped IE8 support, then all browsers are mostly covered and is definitely a lot nicer/neater than needing a height/width or using display:table and display:table-cell hacks.

If IE8 and down matters, then there are polyfills available for this functionality.

I have written about a much better (IMHO) solution that does not need the height be declared and does not use tables.


Very nice. When I actually stop to think about it, it's amazing to me that this is not immediately easy to do. Things like this give credence to Bret Victor's most recent talk.

HTML/CSS is generally quite flexible when it comes to operations on text. No surprise since it was its intended purpose to be a format for documents.

Making any layouts and god forbid centering elements has always been a headache for me. Even by looking at the CSS examples provided by the link my first thought is how random they all seem and how ugly they are not to mention difficult to remember and use. There should be a single way to center an element. It should be an obvious operation given how important and common it is.

Some very useful CSS properties might take a lot of code and be hard to implement in native GUI toolkits like floats, overflow, height/width with percents, text wrapping etc. This is a sweet spot where HTML/CSS shines.

I have been playing with QML lately and decided to implement the Dialog (Absolute center within viewport) that pops after visiting the linked page just for comparison:

Here's the dialog equivalent that just fills the entire screen of an application done with QtQuick 2.0 for Desktop.


Layouting is easily done by anchors. Filling a rectangle to match a parent's container, centering an element inside a parent, etc. Other containers such as Rows, Columns or Grids are also provided. Property bindings are used for centering the dialog even if the viewport changes. Text wrapping is also done explicitly and binding was necessary to limit text width to the ScrollView for it to work.

One big difference compared to CSS is that by looking at the source I can see at glance what the layout structure is and what might be happening with the element.

Another cool thing about QML is that it's as simple as taking the code, creating a new file 'Dialog.qml', adding a few properties, a signal and some functions and we get a reusable standalone component:


that is very convinient to use:


result: http://i.minus.com/iGTQhAxP55bBP.gif (3MB gif)

How is that better than CSS?

http://jsbin.com/ezocec/1/edit (25 lines counting the HTML)

CSS has columns and grids, custom text wrapping. These features are available now in >90% of browsers. The `.dialog` class can be used as component without any changes, and we have things like component.io and browserify to package them up with behaviour.

result: http://cl.ly/2w1o3h0i1t0r

Sure, at this point HTML/CSS has grown to accomodate many features. But there's a lot of ugly and non-obvious cruft that has been inherited over the ages and it won't change soon.

Perhaps a tool can bundle resources, but in the end it's still going to be inserted into the DOM and can potentially clash with other code since everything lives in a global namespace. There's also the problem of competing tools and the dilemma of which one to choose. Any other additional library that is meant to augment/fix HTML/CSS is another dependency that can cause problems and needs to be maintained.

QML is meant to be extensive. Not happy with how the drop shadow works? Write your own shader that does it the way you want it. Feeling that there's some primitive like an Ellipse missing? You can write your own in C++ and expose it to QML easily. In fact you can expose any native code to QML.

With HTML/CSS you are constrained to the environment it works in.

QML supports components, animations, transitions, particles, states, bindings, i18n and much more. It's also very smooth, qml is hardware accelerated. In the case of CSS so you get some hardware acceleration only for animating properties like translation, etc.

Here's the dialog I posted before which I changed to support states and transitions and also added an inline shader and particle emitter:


http://i.minus.com/iATg82IRCaMa9.gif (result 4MB gif)

As it can be seen it's highly declarative and it basically contains no javascript logic at all besides setting the states.

Of course a lot of such features are available indirectly in HTML/CSS by piggybacking on third party libraries/frameworks, but wouldn't HTML be so much nicer if it were designed with those things in mind from the very beginning?

Now you're pushing it, but it's getting there :)

Shadow DOM is the specification that will fix the collision/cascading issue, making it possible to isolate components. You can now write your own shaders, use custom masks/clipping etc, and of course, SVG for unlimited vector shapes. If that's not enough, write your own graphics layer with WebGL or Canvas.



Now around ~80% less code.

This is a fun but pointless showdown of course, these are technologies born worlds apart, with different audiences, purposes and constraints. HTML appeared in 1990, with the sole purpose of marking up hypertext, grew organically and has a hundred other interoperability concerns; QML showed up in 2009 (?), twenty years later, and was designed to solve specific problems. I'm certain the web wouldn't have grown as fast if it didn't have a stack as accessible as html/css.

This is interesting but I don't like it. It's a quirky non-idiomatic hack. Using vertical-align/line-height/inline-block is equally-effective and IMHO conceptual and readable/self-documenting.

Details: http://jsfiddle.net/uy64k/6/

This requires no extra markup, but it does require the font-size and line-height to be reset.

We use this same technique in Firefox to center images when viewing them standalone, inspect http://www.elizabethtownfamily.com/wp-content/uploads/2012/0... to see for yourself :)

Don't forget to sacrifice at least one goat, if you want cross-platform, standards-compliant code.

I came up with a similar solution a while back [1]

[1] http://stackoverflow.com/questions/5009864/using-all-four-po...

Vertically centering dialog boxes in a window is a minor pet peeve of mine. Boxes should be slightly above center.

If I recall correctly, the original Mac UI guidelines specified that the midpoint of the box should be 1/3 the distance from the top.

What is performance loss/gain compared to Javascript solution of this problem?

There's an infinite performance gain for browsers that have javascript turned off or use noscript.

Other than that, I'd say that doing this kind of stuff in CSS would by default be much faster in a web page context.

What if I don't want fixed dimensions? Maybe media queries could help a bit, but Javascript usage seems to be inevitable.

ps. I didn't mean pure javascript solution anyway:)

If you don't care about older browsers [1], you can use Flexbox to do all sorts of dynamic, fluid positioning.

[1] http://caniuse.com/flexbox - it's in the current version of all browsers (some still prefixed).

Those CSS class names are unacceptable. (:grin:)

Doesn't work with NoScript. Bad example.

Huh? This solution doesn't use any javascript.

Regardless, with ScriptSafe (Chrome) enabled, all I see is a blank page.

I've got to enable assets. and s.codepen.io to see the page rendered.

That appears to be due to the use of an iframe from s.codepen.io for the content.

It's a shame that we need to hack layouts to work with language designed for changing fonts and colors.

It's still impossible if you'd like to center a div that resizes itself depending on the content.

nope, consider: http://codepen.io/KatieK2/pen/ucwgi or http://jsbin.com/uqutol/3/edit

These have intrinsically sized (autosized) boxes that vertically and horizontally center in some container.

not sure how people who "know CSS" can work without knowing this...

There are other ways to center elems, and once you learn another such way (and it consistently works for you), is there any point in researching alternatives?

There is anything new here ?

Why do you need this to center a box in css? It can be done without this too.

How is this related to hacking now again?

this is good

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