5

I am having an issue with making <img> flexible inside a flex parent. Image start exceeding parent dimensions. I would like to leave parent with display: flex; and restrict image from crossing parent's dimensions.

.full
{
  width: 400px;
  height: 200px;
  background-color: blue;
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
}
.half
{
  width: 50%;
  background-color: red;
  padding: 20px;
}
img
{
  width: auto;
  height: auto;
  max-width: 100%;
  max-height: 100%;
}
<div class="full">
  <div class="half">
          <h1>title</h1>
          <img src="http://placehold.it/90x200">
  </div>
</div>

Can you please explain and give some useful links that would explain the shown behavior and possible solution of it?

I am using both Firefox and Chrome to view that. Issue persist in both browsers.


It seems that question is duplicate of this question

hrust
  • 734
  • 1
  • 11
  • 34
  • 3
    TLDR of the duplicate, change the alignment of the flex container to `flex-start`, the issue is the stretch – Temani Afif Aug 22 '18 at 19:32
  • 1
    @TemaniAfif adding `justify-content` doesn't seem to fix the issue (as the snippet shows) – hrust Aug 22 '18 at 19:36
  • @TemaniAfif More than parent does not expand to accommodate child as described in the possible duplicate question/answer. – hrust Aug 22 '18 at 19:43
  • yes the duplicate deal with more things no present here, but I didn't find another one like yours ... and it's not justify-content but `align-items` ... probably Michael_B or someone else will find a better duplicate – Temani Afif Aug 22 '18 at 20:19
  • 1
    @hrust, you are the first person which I have ever seen, who has marked his own question as a duplicate! Incredible! My respect to you! – Bharata Aug 23 '18 at 15:02

1 Answers1

3

In order for it to work .half div also needs to be a flexbox container and the image needs to have min-height: 0, as explained here.

.full
{
  width: 400px;
  height: 200px;
  background-color: blue;
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
}
.half
{
  width: 50%;
  background-color: red;
  padding: 20px;
  display: flex;
  flex-flow: column nowrap;
  justify-content: flex-start;
}
img
{
  min-height: 0;
  max-width: 100%;
  max-height: 100%;
}
<div class="full">
  <div class="half">
    <h1>title</h1>
    <img src="http://placehold.it/90x200">
  </div>
</div>
Michał Drabik
  • 425
  • 4
  • 8