
Absolute Horizontal And Vertical Centering In CSS - imd23
http://coding.smashingmagazine.com/2013/08/09/absolute-horizontal-vertical-centering-css/
======
gmjoe
Vertical centering isn't that useful when you already have to know the height
of things... I mean, if you already know the heights, you can just put the
numbers in straight.

The best way to do _real_ vertical-centering that works with variable heights,
and doesn't use JavaScript, is to take advantage of the fact that table cells
do this with "vertical-align: middle". Inexplicably, _only_ table cells allow
true vertical centering with variable heights.

So you can either convert the surrounding element to a big ole
<table><tr><td></td></tr></table>, or you can use CSS to give it a property of
display: table-cell. And in both cases, give it a "vertical-align: middle".
Then you're good to go!

And of course, horizontal positioning in the table cell is easy.

~~~
ggurgone
you can do (real) vertical-centering with display: inline-block too

See
[https://twitter.com/giuseppegurgone/status/38820349236545126...](https://twitter.com/giuseppegurgone/status/388203492365451264)

~~~
gmjoe
Very interesting, I never saw that before!

But I can't figure out, for the life of me, why the bizarre
".container:before" declaration is needed -- it would seem to be entirely
superfluous, but if you remove it, the whole thing breaks. Can you explain
what's going on?

~~~
ggurgone
Here is a visual explaination:
[http://dabblet.com/gist/7359467](http://dabblet.com/gist/7359467)

The pseudo-element (in red) is 100% tall and both .container:before and
content are inline-block with vertical-align: middle;

------
pmichaud
The fact that this is an interesting article is a huge indictment of CSS. It
was developed for a different, simpler use case, and it's obviously the wrong
abstraction at this point. Too bad it's entrenched.

~~~
brandonbloom
I've been saying this of JS/HTML/CSS for years, but people seem to suffer from
severe stockholm syndrome.

~~~
morley
What do you suppose we do about it? Like it or not, people use web browsers to
access the Internet, and as long as web browsers render HTML and CSS, we have
to use the tools we have.

~~~
brandonbloom
My complaint is that a lot of people _like_ CSS/HTML/JS. Because they have
learned it and gotten comfortable with it. They don't know/understand anything
else and their identity and sense of self-worth is challenged if you speak ill
of these technologies. That's a big problem.

Pragmatically: I suppose that we embrace CSS/HTML/JS as object code. And I
mean this in a much more dramatic way than CoffeeScript or SASS. This is
finally starting to happen, thanks to browser support for things like source-
maps. This is one reason I contribute to ClojureScript!

Idealistically: We should be pushing for lower level platforms for code
distribution and execution, as well as host platform integration. Portable
Native Client and similar efforts shouldn't be so controversial.

------
phelmig
Next time when I want to explain why HTML/CSS can be a pain, I'll take this
example.

"Imagine it's 2013 and there is a website that has been online for years,
where the greatest hackers and entrepreneurs exchange exciting ideas. When
somebody posted an easy solution how to center something in HTML horizontal
AND verical it was the favored post on that site for a day" ... ;)

------
recuter
Before the inevitable complaints about CSS start flying in, you really
actually hate the Box Model and should direct your anger towards it. To wit,
the article itself says:

"Other Techniques

Absolute Centering is a great solution for centering, but there are other
methods that may fit more specific needs. The most commonly used or
recommended methods are Negative Margins, Transforms, Table-Cell, Inline-
Block, and now Flexbox. They are covered more in depth in other articles, so
I’ll only cover the basics here."

Pray your support matrix allows you to just stick to Flexbox soon and all of
this will start to feel like a bad dream from the bygone past.

First we abused tables, then we abused divs, now there are actual sane hooks
for this, it just took 20 years is all.

------
eeeeaaii
I personally think it's just incredible that vertical centering in CSS has
been so woefully neglected over the 16 years we've had CSS. Every time I read
another article about how somebody just maybe has figured out a kludgy way to
vertically center things with CSS, I just shake my head. Aren't there any
graphic designers on any of the W3C working groups surrounding CSS? Back in
the old days when everything was a table-based layout, there was a clean, one-
to-one mapping between the grid framework that your graphic designer created
and the code underlying the page.

Then the semantic web pedants came along and decreed that tables shall never
be used for layout. Fine -- but nobody ever bothered to come up with a
DIVs+CSS replacement for the grid-based layout that any serious graphic
designer uses to build a page.

And do you know what happened to the web? Debate cause and effect all you
want, but webpage designs are far more boring now than they were 10 years ago.
Now it's all just blocks of large-print scrollable text, some images here and
there (or maybe a wall of them), and a cute logo. It's like everything is a
Geocities page with better fonts and color choices, minus the gifs. I feel
like I never see anything really cutting edge or creative in the design space
on the web.

The internet is a really young medium of course, and it will naturally go
through phases, where certain types of design come into fashion while others
go out. And I would love it if somebody would prove me wrong by posting some
links to some really kick-ass-looking sites. But from where I'm sitting these
days, from a design perspective the web is a big yawnfest. Maybe today's
websites are more usable and easier to index and work well on a screen reader,
but from a graphic design perspective... zzzzz....

------
Aardwolf
I'm wondering, why does even CSS3 not have a simple way to vertically center
text (or even vertically center anything)? It's a pretty basic and wanted
thing afaik... Seems like a higher priority than shadows and 3D effects to me.

------
cletus
The history of CSS is one where Microsoft earned an awful lot of bad will and
what an epic fail the W3C has been in this regard.

Microsoft of course deviated from the nascent "standard" such that we've been
burdened for years with "if IE ..." blocks to the point that the latest
version of IE pretends not to be IE.

You reap what you sow.

But every time I come across the issue of "how to vertically center in CSS",
an issue that has existed for years, I get angry. I get angry because the old
way (vertical alignment on table cells) just works. As much as the CSS purists
(some might call them "anti-table zealots"), it's hard to argue with something
that works all the way back to IE4 and probably beyond (well valign="middle"
probably does, CSS vertical-align: middle is probably IE5/6).

But beyond this there are so many things in HTML/CSS that should be simple but
are hard. This is just one of them.

Consider spacing between table cells. There's (still) actually no way to do
this... if you want no spacing between the leftmost and rightmost cells and
the edge of the table, which I find is a pretty good use case. People end up
doing things like:

    
    
        td { margin-right: 0.3em; }
        td:last { margin-right: 0; }
    

Any such solutions had varying backwards compatibility issues, a problem we're
now largely getting behind us, but still...

Why can't I specify (separately if need be) the vertical and horizontal
spacing between cells separately to the edge of the table (which should really
be a property of the table rather than the cells IMHO).

The problem here is that the CSS WG seems to have started with a model and
then just run with it without running it through very common use cases.

Looking at the article, it looks fine. One thing I'll say is it starts off
with the "margin: 0 auto" trick, which everyone who does anything with CSS
needs to know. Why is centering that hard? Why can't I just say "put this in
the center"? Why can't I then use margins to offset from center or something?

Also FWIW, the margin: 0 auto thing didn't work in older versions of IE if you
didn't specify a DOCTYPE and force "standards compatibility mode" (rather than
the euphemistic "backwards compatibility mode".

------
pete_b
There are, in-fact, and have been for a while several known ways do do this in
CSS 2.1 this just being another with a similar long list of restrictions and
context requirements.

[http://css-tricks.com/centering-in-the-unknown/](http://css-
tricks.com/centering-in-the-unknown/)

They're all much of a muchness, at least we'll be able to just use flexbox
soon enough.

------
nerfhammer
It's so frustrating that it still requires all sorts of gymnastics to do
something so conceptually simple in CSS, and yet many people seem to see CSS
as a self-evident imperative to be used in all cases.

------
jdmitch
_> This will break cross-browser compatibility._

That kinda ruined all the excitement for me :( Good of the OP to include all
of the alternative techniques that might be better for cross-browser or other
specific situations.

Seems like transforms are better than the original main suggestion though...
why not stick with those?

------
proksoup
Also same link was on HN 84 days ago
[https://news.ycombinator.com/item?id=6214314](https://news.ycombinator.com/item?id=6214314)

------
proksoup
Stephen Shaw's (author of the OP article) codepen of the same I sometimes find
easier to read, less advertising noise than smashing ...

[http://codepen.io/shshaw/full/gEiDt](http://codepen.io/shshaw/full/gEiDt)

------
aschearer
I'm curious why there isn't something like TypeScript or Coffeescript for CSS?
I'm aware of LESS and SASS but to my knowledge they don't go as far as their
JavaScript complements in adding future-looking functionality. Is it simply
not possible to add CSS grid or flexbox (or both!) support to LESS and have it
compile down to plain ol' CSS?

~~~
swordfish0321
Not sure what you mean by "future-looking functionality". I don't know
anything about TypeScript but CoffeeScript is just an opinionated way to
generate JavaScript. Isn't that what both LESS and SASS do for CSS? Regarding
grid or flexbox, that is ultimately a design decision/preference of the
architect.

So using your example, if SASS inherently used grid that would be like
CoffeeScript introducing MVC into your project.

~~~
aschearer
TypeScript adds some features planned for Javascript such as classes with
inheritance and modules. The thinking is that when these features become
standardized your TypeScript code will be valid Javascript. (Or at least as
far as those features are concerned.) So in the same vein, why doesn't SASS
provide the next generation of CSS functionality? That is, you use the
proposed syntax for CSS grids and it transforms that into whatever mess is
necessary to emulate it in today's CSS. Later when CSS grid support is
available no translation is necessary.

I suppose the answer is because it can't do so in CSS alone and that emulating
CSS Grid would require CSS, DOM, and Javascript to be emitted from the
compiled SASS script. It would be neat if someone who knew more could confirm
my suspicion.

I'm not sure I follow your example regarding CoffeeScript and MVC.

------
tomasien
This is the first time in my life going to HN while I'm futzing with a problem
has actually helped. Thought I was going to take my mind off - instead I found
the answer immediately!

------
mistercow
I can't wait until the new version of flex box has widespread support and we
can stop relying on these dumb hacks to do the most basic layout operations in
CSS.

------
camerondaigle
Good grief, if the element to be centered has a fixed height and width, then
there's nothing to this. I've been using the negative margin method for years:

[http://jsfiddle.net/mBBJM/2155/](http://jsfiddle.net/mBBJM/2155/)

Not that it's any less Stockholm-Syndrome-y than the linked article's
solution, but still, I have no clue why this is on the front page of HN.

~~~
Segmentation
Front-end stuff always seems to make the front page of Hacker News. I think
it's because front-end is easier, and possibly more "hip" right now (as far as
jobs go), so there's more interest in it.

~~~
nostrademons
I'm a full-stack engineer that started out on the front end. I don't think
frontend is easier - in terms of the amount of background you need to know to
produce something useful, being a frontend engineer is significantly harder
than being a backend one. However, frontend stuff _demoes better_. If you do a
fancy machine-learning analysis of some public data set but present it as a
command-line app or a table on some bare-bones website, people will be like
"Uh, what's the deal?" If you make things fly around the screen in cool
patterns, they'll be like "Woah! I didn't know you could do that!"

A lot of this is also because a frontend engineer's job is to lower the
cognitive processing a user has to do, while a backend engineer's job is to
come up with useful things to cognitively process. In other words, when a
backend engineer comes up with a demo, they make the viewer _work_ to
understand it, while when a frontend engineer does the same they make the
viewer go "Ooh! Aah!"

~~~
camerondaigle
Fair enough. This seems like CSS Positioning 201 to me, but I've been dealing
with this stuff for a long time now, so my perspective is probably pretty
skewed.

I completely agree with your point re: cognitive processing: good CSS
communicates _intent_ to the reader, so if this kind of stuff is unclear to
people and the Smashing Mag post helps the concept click in readers' minds,
then it's a win :)

------
ape4
What about using the HTML5 calc() to figure out the center?

~~~
svachalek
If you are willing to use something as bleeding-edge as calc, you may as well
do it the right way:

[http://philipwalton.github.io/solved-by-
flexbox/demos/vertic...](http://philipwalton.github.io/solved-by-
flexbox/demos/vertical-centering/)

~~~
djKianoosh
Only that doesn't work in IE10 :(
[http://caniuse.com/#search=flexbox](http://caniuse.com/#search=flexbox)

------
ffrryuu
CSS grid is the future.

