Learn how to prevent CSS’s Flexbox from stretching your image horizontally.
Flexbox has an odd default behavior where images get stretched horizontally to the full width of its parent container. So if you have a parent element (flex container) with flex-direction: column
and a child element (flex item) which is an image, then the image’s natural height is maintained while the width is stretched as wide as the parent container.
This behavior is inconsistent, depending on your browser’s default CSS stylesheet (User Agent Stylesheet).
Fortunately, the solution is simple. You just need to replace your image/flex item’s align-self
property’s default stretch
value with another value.
Instead of stretch
you can use center
, which will remove the image stretching, and vertically align your image in the middle of its parent container.
img {
align-self: center;
}
Example
Check out the following CSS example where we have 1 parent (flex container) and 2 children image elements (flex items) inside.
- The first image element has the browser default
align-self: stretch
which ruins the aspect ratio. - On the second image element, I added a utility class called
.self-center
, with thealign-self: center
declaration which removes the stretching:
https://codepen.io/StrengthandFreedom/pen/qBBoMOX
Glorious, problem solved!
Note: you can also use top
, to vertically align your image to the top of its parent container.
img {
align-self: top;
}
Both methods will remove the stretch value from your image, but whether you should use top
or center
depends on what you want to do with your images.
Good to know
Flex items have a default align-self
value of stretch
. So whether your flex-item (child element) is an image or another HTML element, it gets stretched horizontally by default.