Why does flexbox stretch an image?

Flexbox has this behavior when it stretches images to their natural height. In other (more specific) words, if I have a flexbox container with a child image and I resize the width of this image, the height does not change at all and the image is stretched.

<div> <img src="https://loremflickr.com/400/300" > <h4>Appify</h4> <p> some text </p> </div> 

And this style sheet

 div { display: flex; flex-wrap: wrap; } img{ width: 50% } 

I added this code to demonstrate what I mean. What causes this?

+87
html css flexbox
Jun 03 '16 at 8:33
source share
5 answers

It is stretched because align-self is stretch by default. Set align-self to center .

 align-self: center 

See the document here: align-self

+192
Jun 03 '16 at 9:07
source share

Key align-self: center :

 .container { display: flex; flex-direction: column; } img { max-width: 100%; } img.align-self { align-self: center; } 
 <div class="container"> <p>Without align-self:</p> <img src="http://i.imgur.com/NFBYJ3hs.jpg" /> <p>With align-self:</p> <img class="align-self" src="http://i.imgur.com/NFBYJ3hs.jpg" /> </div> 
+7
Apr 10 '17 at 19:14
source share

I had the same problem with the Foundation menu. align-self: center; not working for me.

My solution was to wrap the image with <div style="display: inline-table;">...</div>

+1
Jul 27 '17 at 20:58
source share

Adding margin to align images:

Since we wanted the image be left-aligned to left-aligned , we added:

 img { margin-right: auto; } 

Similarly, to image right-aligned to right-aligned , we can add margin-right: auto; The snippet shows a demo for both types of alignment.

Good luck ...

 div { display:flex; flex-direction:column; border: 2px black solid; } h1 { text-align: center; } hr { border: 1px black solid; width: 100% } img.one { margin-right: auto; } img.two { margin-left: auto; } 
 <div> <h1>Flex Box</h1> <hr /> <img src="https://via.placeholder.com/80x80" class="one" /> <img src="https://via.placeholder.com/80x80" class="two" /> <hr /> </div> 
0
Apr 17 '18 at 3:20
source share

use a display block for an image that exists inside a flex container

0
Oct 22 '18 at 11:30
source share



All Articles