
“Googles 'vertical center div css' for the 100th time. reads for 7 minutes” - sebkomianos
http://www.bleonard.com/blog/2015/08/01/teaching-css/
======
jonahx
One of the wonderful ironies of CSS is that after years of puritanical
preaching about the evils of non-semantic table elements, the best-practice
recommendation for centering a div of unknown dimensions, assuming you want
any kind of legacy support, is[0]:

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

[0]
[http://howtocenterincss.com/#contentType=div&horizontal=cent...](http://howtocenterincss.com/#contentType=div&horizontal=center&vertical=middle&browser.IE=8)

~~~
pault
One could make the argument that having table layout behavior decoupled from a
specific tag is a perfectly desirable state of affairs. One of the issues with
using tables for layouts is the massive clutter of row and cell tags that make
the markup extremely difficult to read. Being able to assign those behaviors
when and where you need them is the best of both worlds.

~~~
jonahx
The irony is that what we are doing, semantically, is "centering." Yet to
express that concept we are forced to refer to the entirely unrelated concepts
of tables and cells, only because of the historical accident that table
elements were the only way you could do many types of centering because CSS
lacked basic facilities for layout.

Also, naming issues aside, we are forced to pollute our markup with pointless,
unsemantic container divs simply to achieve a basic style on the contained
div.

~~~
rimantas
I doubt you understand what the word "semantically" means. I don't see how
polluting markup with <table> (and tables were often nested), <tr> and <td> is
any better, not to mention that often already existing markup was sufficient
and no extra was needed. Also, div's by definition have no semantic meaning,
and that's a good thing—those who bothered to care know that tables for layout
had their share of accessibility issues. Alas, now when most race to stuff as
much anuglar bootstraps ino their SPA nobody cares about semantics and
accessibility any more.

~~~
Udik
I think he's right. The syntax says "display this stuff as a table and a table
cell", but what in fact we _mean_ is "center this thing". The fact that both
"style as a table" and "center" attain to the visual aspect doesn't change the
fact there is a semantic difference between the two.

Also, if divs have no semantic meaning in the context of the document's
structure, it means they serve some other purpose: and that purpose is visual
styling (not directly but through a css applied to them). How is this not a
violation of the separation between document structure and presentation?

~~~
olavk
It is in principle a violation of the separation between structure and
presentation, but it is not a violation of the semantics of HTML which is a
bigger issue. Since div's are semantically neutral in HTML, a multitude of
"presentational divs" will not confuse screen readers and so on, as the use of
<table>-elements will.

That said, separation between structure and presentation is desirable, and the
necessity to use multiple divs to achieve a layout effect means CSS 2 is not
as powerful as we could want. The grid model in CSS 3 is much more powerful,
and allows things like separating the presentation order from the structural
order.

------
dennisbest
Just use flex-box. And by "use", I mean get ready to study it, change the way
you write CSS, give it all of your worldly possessions, and eventually collect
money for it at the airport.

~~~
netghost
That is, assuming you don't need to support older browsers like ie9 or ie8...

~~~
n0us
or ie10...

~~~
turing
IE10 supports flexbox, it just supports the 2012 syntax.

------
Animats
You see, kiddies, we used to have programs that did all that for you. There
was this program called Dreamweaver. You just opened up a design window and
laid out the page by pointing and clicking. Anyone could do it. But if anyone
could do it, "web programmers" weren't needed. So CSS was invented to make it
more like programming, and especially to make it so complicated that it
couldn't be done by pointing and clicking.

~~~
bbcbasic
> more like programming

Yes i.e. DRY

~~~
cousin_it
DRY notwithstanding, I agree with Animats that design should be done visually,
not programmatically. Using code for layout is just as bad as programming by
flowcharts. Programming tools should reflect how a programmer thinks about the
problem, and design tools should reflect how a designer thinks about the
problem. Expensive "web programmers" shouldn't be needed for web design, just
as "print programmers" aren't needed for print design.

~~~
nathan_long
> Expensive "web programmers" shouldn't be needed for web design, just as
> "print programmers" aren't needed for print design.

You don't need web programmers for web design. You can export from a WISYWIG
to HTML, or design a big ol' GIF and post it on Wordpress. Lots of restaurants
do that sort of thing.

But you probably want something that interacts with the user, changes layouts
based on screen size, provides information to disabled users, validates and
submits information, allows commenting and moderation of comments, etc. Eg, a
program. And you do need programmers for that.

~~~
cousin_it
> _changes layouts based on screen size_

Why can't the designer specify that? Because the current tools suck for
designers (i.e. they were made for programmers).

> _provides information to disabled users_

Ditto.

> _allows commenting and moderation of comments_

There should be ready made solutions for that, usable by non-programmers. If
you wanna buy a toaster, you don't go "oh, it's an Electrical Device and we
need an Electrical Engineer". A toaster is complicated inside, but it was made
with good engineering so users don't have to care.

The web is not like that. The needs of most websites are well understood by
now, but somehow we still need programmers to make layouts and comment
systems. My only explanation is that the whole system of HTTP/HTML/CSS/JS is
poorly designed, in a way that's very hard to fix. Name me one other medium
where positioning elements on the screen/page/whatever isn't a completely
solved problem. Show me a single game developer who just can't seem to get the
crosshair centered vertically on the screen.

------
lkrubner
This is an example where the headline on Hacker News is 100x better than the
original headline. I do wish Hacker News allowed these kinds of headlines,
which draw out the parts of the article that are of most interest to the
Hacker News crowd.

~~~
jonahx
I upvoted based on the headline before I even started reading, which I rarely
do.

------
supercoder
All you need to do is simply take the 20 part video course
[http://flexbox.io/](http://flexbox.io/). Couldn't be easier !

------
bla2
This is has been a problem for a long time, but it's fixed now:
[https://philipwalton.github.io/solved-by-
flexbox/demos/verti...](https://philipwalton.github.io/solved-by-
flexbox/demos/vertical-centering/)
[http://caniuse.com/#feat=flexbox](http://caniuse.com/#feat=flexbox)

~~~
sago
It'll be a while, sadly. IE8-10 are still up to 25% of the browsers[0]
(caniuse puts them much lower, which isn't surprising for sampling dev
oriented sites). IE10 (5% of that) needs a different syntax, and 8-9 don't
support it. All three support table layout[1], which is why it is still the
best solution if you care about compatibility.

[0] [https://www.netmarketshare.com/browser-market-
share.aspx?qpr...](https://www.netmarketshare.com/browser-market-
share.aspx?qprid=2&qpcustomd=0&qpcustom=)

[1] [http://caniuse.com/#feat=css-table](http://caniuse.com/#feat=css-table)

~~~
hatsix
I doubt the author's daughter cares about legacy browser support.

~~~
sago
A dismissive dev's 'legacy' browser, is 25% of actual web users. You can
dismiss them as legacy if you like, but there isn't a minimum age before you
get told your site sucks because a quarter of people get crap when they load
it.

I pretty sure my kid would care if that happened.

~~~
jfoster
Those versions of IE might represent 25% of web users, but any given website
will probably see them as much less than 25%.

I run multiple sites, and most of them have IE (any version) as under 10% of
users. One of them doesn't; IE represents ~13.5% of users on that one.

My untested theory about this is that IE users are generally less adventurous
web users, sticking to sites like Gmail, YouTube, local news sites, etc.

TLDR: unless you're working on Gmail or a site where you expect to soon see
the world turn up at the doorstep, it might be safe for you to mostly ignore
IE.

~~~
jacquesm
My proven theory is that if you don't support users with particular browsers
those users will tend to no longer support your website in return.

~~~
jfoster
I agree; that's where it gets a bit tricky. You're not going to have many
repeat customers who can't use your product.

You have to either be enhancing an existing product where you know that the
segment in question isn't worthwhile supporting, or be prepared to estimate
whether that segment is going to be meaningful for you.

Another thing to keep in mind is that sometimes the result isn't a deal-
breaker. Suppose I try to get vertical centering working on one of my sites
using flexbox. Perhaps the 5% IE users simply see the content of each div at
the top rather than being vertically centered. Not ideal, but not the worst
possible outcome, either.

Out of interest, does anyone know how flexboxes break on IE if you try to use
them for vertical centering? Does the content actually just sit at the top?

~~~
jacquesm
The problem is that 25% of your customers could easily represent 100% of your
profits. So by the time you're done with all your fixed costs and still need
to turn a profit having a few % more or less users may make the difference
between a company that will succeed or one that will tank.

That's why any commercial entity will be _very_ wary of closing the door on
paying users no matter how old their setup is.

------
grumblestumble

      .centered {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
      }
    

now just put it in a relatively positioned container and you're done. i
thought this was common knowledge by now, i haven't used `table-cell` in
years.

~~~
inopinatus
Isn't this the construct that exhibits blurring problems due to subpixel
alignment in Gecko / Webkit ?

------
bleonard
Follow-up: Does anyone know how to best host this site? a) with less than 50
users all-time b) easily updated daily (blog-style) by a 7 year old c) is
approximately free

Wordpress with her custom theme seems to fail C. Github pages / Jekyll is
failing B

~~~
paulcole
NearlyFreeSpeech can host a wordpress site with low traffic for little more
than a penny a day.

~~~
unknownknowns
Was going to comment this. Used NFS years ago and was incredibly happy with
them, they're fantastic.

~~~
paulcole
Yeah, I have a handful of low-traffic sites with them and it's fantastic.

For a little more functionality, I like ASmallOrange. My partner hosts her
site/blog with them for $35/year and it's great, too.

------
rsuelzer
This was a cute article. I laughed at the end. Thank you for sharing this, it
put a smile on my face. :)

------
willstepp
display:table and its kin are the greatest thing I ever discovered in css. No
more centering problems and easy to reason about. I'm not sure if people just
don't know about it, or there are use-cases where it doesn't work for them.
I'll definitely use Flexbox when its more widely supported, though.

~~~
pault
They don't wrap when their parent container shrinks, but sometimes that's the
behavior you want (navigation bars for example), and media queries get around
those issues nicely.

------
elixx
At which point you use a bootstrap jumbotron like 2/3 of the sites I see.

------
nathan_f77
I love "display: flex" so much. I'm working on extensions for modern browsers,
so I can use it everywhere. Makes everything so much easier. Also cases where
you would normally use ".left { float: left; }" and ".right { float: right;
}".

------
logicallee
Why isn't this actually an easy, obvious part of CSS? It doesn't seem like
there is anything that makes this more complicated to implement than anything
else people use daily... it's also an obvious feature. Reasons?

------
zajd

      body { position: relative; height: 100vh; }
      #content { height: <defined>; top: 0; right: 0; left: 0; bottom: 0; position: absolute }

------
vayarajesh
A father-daughter moment of a techie :) your daughter see you as a hero when
she learns more about vertical center and CSS in general

------
mattwad
If you know the height of your centered box, it's not _that hard_. Create a
wrapper div whose top is set 50% down the page but has a negative offset which
is 50% the height of the box:

    
    
      .vertically-centered {  
        position: absolute  
        top: 50%;  
        height: 200px;  
        margin-top: -100px; /* minus half of `height` */  
      }
    

If you have trouble, try setting `height` to 100% on the <body> tag and any
parents

------
bbcbasic
And if you google 'vertical center div css' you will now find this page (in a
news subsection). Try it. Ymmv.

------
jnpatel
Aw man, I was hoping to see the final website your daughter ended up with! :)

------
seanwessmith
Why isn't there a MS Word for creating HTML?

~~~
andrewstuart2
Actually, it used to be called Frontpage. It was pretty workable, but if you
were able to figure it out, you were probably better off just learning HTML
and CSS anyway. Creating anything beyond a really basic table layout was
pretty maddening, IIRC.

The typical problem with WYSIWYG webpage builders is that the web is not a
printed document. If you don't know the underlying concepts of layout you
expect things to behave much differently than they actually do. Or at least,
that was how it was for me.

~~~
bkjelden
A copy of Frontpage in middle school is what got me in to programming, back in
the day.

One of my earliest memories of 'coding' (It seems silly to call it that now,
but hey, I was 13!) was opening the generated html files to remove the
"Created with Frontpage" html comments that were automatically injected.

------
throwaway000002
Has anybody, possibly, probably, an academic, given HTML+CSS a semantics?

I'm thinking something like whatever minimal core would be considered the PCF
of the web world.

~~~
rimantas
CSS is about presentation, not semantics, that's the point of it. And the
whole point of separation of concerns. So sad to see stuff like
[http://csszengarden.com/](http://csszengarden.com/) being forgotten and the
whole web standards movement coming to nothing.

------
teen
this is extremely easy to do in flexbox. despite what people say it's actually
very quick to pick up

------
pcunite
Very funny ... thanks for sharing.

------
BurningFrog
But Flexbox?

------
SimeVidas
Tattoo “flexbox” on your hand :P

------
justindocanto
It's really not that hard.

<div class="center-this"><div>Stuff</div></div>

.center-this {display:table;} .center-this > div {display:table-
cell;height:100%;vertical-align:middle;}

I even code pen'd it for you:
[http://codepen.io/anon/pen/RPEypL](http://codepen.io/anon/pen/RPEypL)

