Vertically align an image inside a div with responsive height
Use flexbox - apply display: flex;
and align-items: center;
to your div. This will center the image vertically and adapt to height changes — so smooth, it's flexing!
Flexbox — the gift that keeps on giving. Read on for more techniques!
Understanding vertical alignment
Vertical alignment is a notorious CSS challenge. Here are key techniques to make it a walk in the park!
Method 1: Inline-block alignment with pseudo-element
Create a pseudo-element with display: inline-block;
and apply vertical-align: middle;
for that perfect center:
Method 2: Responsive aspect ratios with padding
Ok, back to math class! Set padding-top
or padding-bottom
to a percentage value to achieve that desirable ratio:
Method 3: Precise centering with positioning and transform
Eat an apple, position: absolute;
and transform: translate
make precision a cinch:
Advanced techniques
Determination is key, but super crafty CSS techniques certainly help.
Technique 1: Display table for the pre-flexbox diehards
Still in a fleeting romance with the past? Try display: table method:
Technique 2: Cross-browser compatibility with flexbox and max-height
Ensuring cross-browser alignment with a mix of flexbox and max-height — almost as complex as a secret sauce recipe!
Technique 3: Preserving the aspect ratio
Maintaining those aspect ratios while the element scales — just like maintaining those diet ratios while your waistline expands:
Advanced fine-tuning
Incredible designs require attention to detail. Here are a few more gems for your toolbox:
Tip 1: Removing white space in inline elements
Remove white space by setting font-size
to zero in the parent container. Yes, CSS often requires a little zen mode:
Tip 2: Handling different image sizes
Flex your muscles and get those varying image sizes centered with percentage margins or transform properties:
Tip 3: Ensuring images stay within their container
For those times you want your images to respect boundaries. A little max-height
and max-width
never hurt!
Ready-made playgrounds & templates
Ever found coding a bit rough sometimes? Playgrounds and templates to the rescue!
- Flexbox playground: JsFiddle Flexbox Example
- Aspect ratio box: CSS-Tricks Aspect Ratio Boxes
- Vertical align samples: JsBin Vertical Alignment
Such play, much fast!
Was this article helpful?