CSS flexbox vertically/horizontally center image WITHOUT explicitely defining parent height

CssFlexbox

Css Problem Overview


With only the parent div and the child img elements as demonstrated below how do I vertically and horizontally center the img element while explicitly not defining the height of the parent div?

<div class="do_not_define_height">
 <img alt="No, he'll be an engineer." src="theknack.png" />
</div>

I'm not too familiar with flexbox so I'm okay if flexbox itself fills up the full height, but not any other unrelated properties.

Css Solutions


Solution 1 - Css

Just add the following rules to the parent element:

display: flex;
justify-content: center; /* align horizontal */
align-items: center; /* align vertical */

Here's a sample demo (Resize window to see the image align)

Browser support for Flexbox nowadays is quite good.

For cross-browser compatibility for display: flex and align-items, you can add the older flexbox syntax as well:

display: -webkit-box;
display: -webkit-flex;
display: -moz-box;
display: -ms-flexbox;
display: flex;
-webkit-flex-align: center;
-ms-flex-align: center;
-webkit-align-items: center;
align-items: center;

Solution 2 - Css

Without explicitly defining the height I determined I need to apply the flex value to the parent and grandparent div elements...

<div style="display: flex;">
<div style="display: flex;">
 <img alt="No, he'll be an engineer." src="theknack.png" style="margin: auto;" />
</div>
</div>

If you're using a single element (e.g. dead-centered text in a single flex element) use the following:

align-items: center;
display: flex;
justify-content: center;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJohnView Question on Stackoverflow
Solution 1 - CssDanieldView Answer on Stackoverflow
Solution 2 - CssJohnView Answer on Stackoverflow