I want an image to shrink but not grow above it’s natural size. The solution given here is working fine:
Make an image width 100% of parent div, but not bigger than its own width
However when using it in a different context it’s still growing above it’s natural size.
section {
display: flex;
}
figure {
margin: 0;
display: flex;
flex-direction: column;
flex: 1;
}
figure img {
/* This image should shrink in a responsive way
but not grow above it's natural size */
max-width: 100%;
}
section p {
flex: 1;
}
<section>
<figure>
<h4>The headline</h4>
<img src="images/the-img.jpg">
<figcaption>
The caption.
</figcaption>
</figure>
<p>
Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata
sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum.
Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.
</p>
</section>
Is there a way to pretend growing by CSS? Achieving this by Javascript would be no problem.
2
Answers
Just wrap your image in a div and the
max-width:100%
will be based on that rather than the flex container.You want an image to shrink but not grow above its natural size. you can achieve this by
Solution 1: using a combination of
max-widt
h andalign-self
properties.just modify the css of img element as:
In the figure img selector, we set the
width
andheight
properties toauto
to maintain the aspect ratio of the image. Themax-width
property restricts the image from growing horizontally beyond its natural size. By settingalign-self: flex-start
, we align the image to the top of the container, allowing it to stretch vertically within the available spaceSolution 2: the same can be achieved by setting an additional
align-items
property toflex-start
,center
orflex-end
on thefigure
css. that will also prevent the stretching of inner img element beyond its natural width.