Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does flexbox stretch my image rather than retaining aspect ratio?

Tags:

html

css

flexbox

People also ask

How do I stop image stretching in CSS flexbox?

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.

How do I make my background image not stretch?

How to fit image without stretching and maintain aspect ratio? Answer: If you want to use the image as a CSS background, there is an elegant solution. Simply use cover or contain in the background-size CSS3 property. contain will give you a scaled-down image.

Why is image stretched?

If you added the image and changed the dimensions right away the image will appear to be missing one of the dimensions. Word reads this incorrectly and in turn stretches the image. You can tell your image might do this because it's missing part of the dimensions like the image below.


It is stretching because align-self default value is stretch. Set align-self to center.

align-self: center;

See documentation here: align-self


The key attribute is 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>

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>


Adding 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 {
  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>