Hacker News new | ask | show | jobs
by ChrisGaudreau 4077 days ago
Would this technique work to center, say, an <img> tag with undeclared dimensions inside of a div? Or do you have to jump through hoops?
2 comments

No, 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.

With 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
An 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.