Vertical Alignment of a Dynamically Sized Image

I’m definitely no expert at CSS. In fact it is usually quite opposite for myself – I take a look at some other examples and figure out what I need to do.

Most recently, I found myself needing to fit a dynamic image inside a div that is 100×100, and I always want it to be correctly proportioned. This dynamic image might be really short and wide or really tall and narrow. I easily found giving the max-height and max-width on the img element to 100px. Set the parent div to text-align: center (got that tip from someone else!). But, I’m still left with the vertical alignment not quite right when looking at really wide images.

I was about to resort to using background images with generated styles on the element, when I found this decent solution. It does require additional markup, but worked out very well for me. Take a look at this fiddle as an example of using an extra “helper” div that is “inline-block” combined with vertical-align: middle.

*Note – I did not create the fiddle – thank you to whoever did!

Leave a Reply