Expand the image to the width of the container when moving to the next line

Is there a way to make the width of the image when it goes to another line in order to take up as much space as possible?

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

I believe that this was achieved using flexbox, but I don’t remember how to do it, and if there are alternative ways to do this, I’m all ears.

script: 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> 
+5
source share
2 answers

Add flex:1 to the image.

Revised script

 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> 
+3
source

Add these lines to .grid img

 flex-basis: 25%; display: flex; flex-grow: 1; height: 100%; width: 100%; 

flex-basis: 25% will only contain 4 images / line

flex-grow: 1 will try to grow images on a line to div borders

width: 100%; height: 100%; will maintain image aspect ratio

Js fiddle

0
source

Source: https://habr.com/ru/post/1247481/


All Articles