Flexbox has this behaviour where it stretches images to their natural height. In other words, if I have a flexbox container with a child image, and I resize the width of that image, the height doesn't resize at all and the image gets stretched.
div {_x000D_
display: flex; _x000D_
flex-wrap: wrap;_x000D_
}_x000D_
img{ _x000D_
width: 50%_x000D_
}
_x000D_
<div>_x000D_
<img src="https://loremflickr.com/400/300" >_x000D_
<h4>Appify</h4>_x000D_
<p> some text </p>_x000D_
</div>
_x000D_
What causes this?
I added This CodePen to demonstrate what I mean.
I faced the same issue with a Foundation menu. align-self: center;
didn't work for me.
My solution was to wrap the image with a <div style="display: inline-table;">...</div>
margin
to align images:Since we wanted the image
to be left-aligned
, we added:
img {
margin-right: auto;
}
Similarly for image
to be right-aligned
, we can add margin-right: auto;
. The snippet shows a demo for both types of alignment.
Good Luck...
div {_x000D_
display:flex; _x000D_
flex-direction:column;_x000D_
border: 2px black solid;_x000D_
}_x000D_
_x000D_
h1 {_x000D_
text-align: center;_x000D_
}_x000D_
hr {_x000D_
border: 1px black solid;_x000D_
width: 100%_x000D_
}_x000D_
img.one {_x000D_
margin-right: auto;_x000D_
}_x000D_
_x000D_
img.two {_x000D_
margin-left: auto;_x000D_
}
_x000D_
<div>_x000D_
<h1>Flex Box</h1>_x000D_
_x000D_
<hr />_x000D_
_x000D_
<img src="https://via.placeholder.com/80x80" class="one" _x000D_
/>_x000D_
_x000D_
_x000D_
<img src="https://via.placeholder.com/80x80" class="two" _x000D_
/>_x000D_
_x000D_
<hr />_x000D_
</div>
_x000D_
It is stretching because align-self default value is stretch. there is two solution for this case : 1. set img align-self : center OR 2. set parent align-items : center
img { align-self: center }
OR
.parent { align-items: center }
The key attribute is align-self: center
:
.container {_x000D_
display: flex;_x000D_
flex-direction: column;_x000D_
}_x000D_
_x000D_
img {_x000D_
max-width: 100%;_x000D_
}_x000D_
_x000D_
img.align-self {_x000D_
align-self: center;_x000D_
}
_x000D_
<div class="container">_x000D_
<p>Without align-self:</p>_x000D_
<img src="http://i.imgur.com/NFBYJ3hs.jpg" />_x000D_
<p>With align-self:</p>_x000D_
<img class="align-self" src="http://i.imgur.com/NFBYJ3hs.jpg" />_x000D_
</div>
_x000D_
Source: Stackoverflow.com