3 ms·
This site doesn't seem to be suggesting absolute centering [1] when it would be the easiest way to center things. "margin: auto" seems to be the way that the d
by pcwalton 12y ago
This site doesn't seem to be suggesting absolute centering [1] when it would be the easiest way to center things.
"margin: auto" seems to be the way that the designers of CSS 2.1 intended to center things. 90% of the time, absolute centering is the easiest way to center in CSS; you should prefer it when possible.
[1]: http://codepen.io/shshaw/full/gEiDt http://codepen.io/shshaw/full/gEiDt
- ChrisGaudreau 12y agoWould this technique work to center, say, an <img> tag with undeclared dimensions inside of a div? Or do you have to jump through hoops?
- pcwalton 12y agoNo, if you don't have a defined height you will need to either use "display: table", the table-cell technique, or flexbox. When I told the site that I had a defined height, however, it still suggested the table-cell trick, which was not the optimal solution because of the extra markup required. In my experience, most of the time when I do want to center something vertically, I have a defined height (which can be a percentage!), so absolute centering is the solution of choice.
- padolsey 12y agoWith no defined height you can still use the `translate(-50%, -50%)` hack, right? I'm kinda surprised it hasn't been mentioned in this thread at all; I use it all the time. http://codepen.io/padolsey/pen/NqKzVG http://codepen.io/padolsey/pen/NqKzVG
- undefined0 12y agoAn image can be vertically aligned with vertical-align: middle; and centered with text-align: center; Firefox uses pcwaltons method for images (resource://gre/res/TopLevelImageDocument.css). Do you want the image to be in the center/vertical of the div (with the div having a specified height)? If so, then pcwaltons method should work, as long as you have position:relative; on the div.