Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

What about cases in which developer wants to vertically center a div, but he or she doesn't want to specify a height property?


"display: table-cell" with "vertical-align: middle" works.


That this is missing is surprising. This method is the most compatible across browsers and only real drawback is the additional markup.


Well, of course it comes with gotchas:

- if that item is "display: table-cell", it must be within a larger element that's "display: table" or "display: table-row"

- "vertical-align: middle" works also for inline-block elements, but that means it's subject to all the other gotchas present in the article about explicit sizing

It eventually makes a kind of sense, but these rules are passed down in folklore and trial-and-error.


Your first point isn’t correct: if you have a solitary element with display:table-cell it’ll generate the appropriate anonymous elements needed for display.

http://www.w3.org/TR/CSS21/tables.html#anonymous-boxes


This article nicely shows all the alternatives with a list of caveats for each: http://coding.smashingmagazine.com/2013/08/09/absolute-horiz...


Then unfortunately you have to calculate it with JS if it varies. Vertically centering divs has always been a gigantic pain-in-the-ass. If anyone has a better idea for doing this without JS, please let me know. Once CSS implements variable-based elements (ie #div.height) then we'll have a lot more control.


> If anyone has a better idea for doing this without JS, please let me know.

Flexbox, with optional fallback to JS for IE 8 and 9. That said, vertical centering is almost always a nice-to-have rather than a must-have so personally I wouldn't even use a fallback.

http://philipwalton.github.io/solved-by-flexbox/demos/vertic...

http://caniuse.com/flexbox


As mentioned elsewhere: "display: table-cell" with "vertical-align: middle".




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

Search: