Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

css

flexbox

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.

like image 313
John Avatar asked Sep 14 '14 10:09

John


People also ask

How do I center an image vertically in flexbox?

All you need to do is add both justify-content: center and align-items:center and flex-direction:column to the Header's CSS rules. You can use this combination of flexbox properties to center any element, not just navbars. Images, divs, etc can all be absolutely centered within a parent element.

How do you center a div vertically and horizontally with flexbox?

To center a div vertically and horizontally using flexbox, you need to wrap the div or div's inside a container with properties ' display: flex; flex-direction: column; justify-content: center;align-items: center; ', then just make the div ' text-align: center; ' if it has text.


2 Answers

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; 
like image 160
Danield Avatar answered Nov 10 '22 07:11

Danield


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; 
like image 38
John Avatar answered Nov 10 '22 07:11

John