Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

flex-grow is not working with images

Currently, I'm trying to make a list. On the left side images which fit into my "display flex layout" and resize on all browsers. My "flex-grow layout" list 1 for the image and 3 for the description. Without images, everything is fine, but with my image (100% width) it does not fit into the 1/3 of the row ...

Does anybody know a solution?

#main {
    height: 100px;
    border: 1px solid #c3c3c3;
    display: -webkit-flex; /* Safari */
    display: flex;
}
#main div:nth-of-type(1) {-webkit-flex-grow: 1;}
#main div:nth-of-type(2) {-webkit-flex-grow: 3;}
#main div:nth-of-type(1) {flex-grow: 1;}
#main div:nth-of-type(2) {flex-grow: 3;}
#main img { width: 100% }
<div id="main">
  <div style="background-color:coral;"><img src="http://www.der-eyecatcher.de/wp-content/uploads/2016/02/Lampe-silber-Schirm_1.jpg"></div>
  <div style="background-color:lightblue;">Description</div>
</div>

<hr>flex-grow without Image<hr>

<div id="main">
  <div style="background-color:coral;"></div>
  <div style="background-color:lightblue;">Description</div>
</div>

Thank you

Simon

like image 955
ABSimon Avatar asked Nov 20 '17 15:11

ABSimon


1 Answers

You have the image container – the flex item div – set to flex-grow: 1. That's fine.

Except the default value of flex-basis is auto (spec).

So, you're telling the item that it's initial main size (i.e., flex-basis) should be the size of its content (the image). That's exactly what's happening. The item takes the natural size of the image.

Add this to your code:

  • flex-basis: 0

OR, better yet, this:

  • flex: 1

which is short for:

  • flex: 1 1 0

which is short for:

  • flex-grow: 1
  • flex-shrink: 1
  • flex-basis: 0

From the spec:

7.2. Components of Flexibility

Authors are encouraged to control flexibility using the flex shorthand rather than with its longhand properties directly, as the shorthand correctly resets any unspecified components to accommodate common uses.

For an explanation of the difference between flex-basis: auto and flex-basis: 0, see this post:

  • Make flex-grow expand items based on their original size

#main {
  height: 100px;
  border: 1px solid #c3c3c3;
  display: flex;
}

/* adjustment here */
#main div:nth-of-type(1) {
  flex: 1;
}

#main div:nth-of-type(2) {
  flex-grow: 3;
}

#main img {
  width: 100%;
  height: auto;
}
<div id="main">
  <div style="background-color:coral;"><img src="http://www.der-eyecatcher.de/wp-content/uploads/2016/02/Lampe-silber-Schirm_1.jpg"></div>
  <div style="background-color:lightblue;">Description</div>
</div>

<hr>flex-grow without Image
<hr>

<div id="main">
  <div style="background-color:coral;"></div>
  <div style="background-color:lightblue;">Description</div>
</div>
like image 55
Michael Benjamin Avatar answered Sep 30 '22 23:09

Michael Benjamin