Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expand Image to container width when moving to next line

Is there a way to make the width of the image, when it transitions into another line to take up as much room as possible?

For example, if the images are displayed next to each other, as soon as one of them drops to the next line, that image on the next line expands to container's width.

I believe I saw this being achieved with flexbox but I can't remember how to do it and if there's alternate ways to do it, I'm all ears.

fiddle:https://jsfiddle.net/jzhang172/6kpyhpbh/

body,html{
  padding:0;
  margin:0;
}
*{
  box-sizing:border-box;
}
.grid img{

  float:left;
  height:100px;

}
.grid{
    display:flex;  flex-grow:2;
    flex-wrap:wrap;
}
<div class="grid">
  <img src="http://www.keenthemes.com/preview/metronic/theme/assets/global/plugins/jcrop/demos/demo_files/image1.jpg" alt="">
  <img src="http://www.keenthemes.com/preview/metronic/theme/assets/global/plugins/jcrop/demos/demo_files/image1.jpg" alt="">
    <img src="http://www.keenthemes.com/preview/metronic/theme/assets/global/plugins/jcrop/demos/demo_files/image1.jpg" alt="">
      <img src="http://www.keenthemes.com/preview/metronic/theme/assets/global/plugins/jcrop/demos/demo_files/image1.jpg" alt="">
        <img src="http://www.keenthemes.com/preview/metronic/theme/assets/global/plugins/jcrop/demos/demo_files/image1.jpg" alt="">
</div>
like image 824
Snorlax Avatar asked Oct 18 '22 11:10

Snorlax


1 Answers

Add flex:1 to the image.

Revised Fiddle

body,
html {
  padding: 0;
  margin: 0;
}
* {
  box-sizing: border-box;
}
.grid {
  display: flex;
  /* flex-grow: 2;   <-- can be removed; not doing anything; applies only to flex items */
  flex-wrap: wrap;
}
.grid img {
  /* float: left;    <-- can be removed; floats are ignored in a flex container */
  height: 100px;
  flex: 1;           /* NEW; tells flex items to distribute available space evenly; 
                        a single flex item on the line will consume 100% of the space;
                        two flex items will take 50% each; etc. */
}
<div class="grid">
  <img src="http://www.keenthemes.com/preview/metronic/theme/assets/global/plugins/jcrop/demos/demo_files/image1.jpg" alt="">
  <img src="http://www.keenthemes.com/preview/metronic/theme/assets/global/plugins/jcrop/demos/demo_files/image1.jpg" alt="">
  <img src="http://www.keenthemes.com/preview/metronic/theme/assets/global/plugins/jcrop/demos/demo_files/image1.jpg" alt="">
  <img src="http://www.keenthemes.com/preview/metronic/theme/assets/global/plugins/jcrop/demos/demo_files/image1.jpg" alt="">
  <img src="http://www.keenthemes.com/preview/metronic/theme/assets/global/plugins/jcrop/demos/demo_files/image1.jpg" alt="">
</div>
like image 146
Michael Benjamin Avatar answered Oct 21 '22 06:10

Michael Benjamin