3 ms·
What about cases in which developer wants to vertically center a div, but he or she doesn't want to specify a height property?
by hawkharris 13y ago
What about cases in which developer wants to vertically center a div, but he or she doesn't want to specify a height property?
- Mandatum 13y agoThen 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.
- markdown 13y ago> 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/vertical-centering/ http://philipwalton.github.io/solved-by-flexbox/demos/vertic... http://caniuse.com/flexbox http://caniuse.com/flexbox
- deleted 13y ago[deleted]
- lobster_johnson 13y agoAs mentioned elsewhere: "display: table-cell" with "vertical-align: middle".
- lobster_johnson 13y ago"display: table-cell" with "vertical-align: middle" works.
- halisaurus 13y agoThat this is missing is surprising. This method is the most compatible across browsers and only real drawback is the additional markup.
- straws 13y agoWell, 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.
- robin_reala 13y agoYour 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 http://www.w3.org/TR/CSS21/tables.html#anonymous-boxes
- ville 13y agoThis article nicely shows all the alternatives with a list of caveats for each: http://coding.smashingmagazine.com/2013/08/09/absolute-horizontal-vertical-centering-css/ http://coding.smashingmagazine.com/2013/08/09/absolute-horiz...