2

I have a div that expands and shrinks depending on the windows size which collapse the images into different rows which I like but how can I prevent the gaps to the right of the screen in the div which is cause by the images not having enough room to fit?

I basically want to center the images horizontally in rows if the images don't have enough room to fit in the previous row which also reduce the div width as well.

This is what I mean visually

How the behavior is right now enter image description here

This is how I want it to act, This is a photo shop pic keep that in mind enter image description here

and I still want to keep how if you resize or expand the div to a certain size the images will reduce in less rows which at times can cause a longer row of images for example.

enter image description here

Here is the code

#container{
  background-color: gray;
  width: 40%;
}

img{
  width: 150px;
}
<div id='container'>
  <img src='http://www.wallpapereast.com/static/images/MTM3NjEyNzY4MzgyNTU5NDc0.jpg'>
  <img src='http://www.wallpapereast.com/static/images/MTM3NjEyNzY4MzgyNTU5NDc0.jpg'>
  <img src='http://www.wallpapereast.com/static/images/MTM3NjEyNzY4MzgyNTU5NDc0.jpg'>
  <img src='http://www.wallpapereast.com/static/images/MTM3NjEyNzY4MzgyNTU5NDc0.jpg'>
  <img src='http://www.wallpapereast.com/static/images/MTM3NjEyNzY4MzgyNTU5NDc0.jpg'>
</div><!--</container>-->

1 Answers1

2

You can achieve a behavior similar to this with CSS Grid Layout:

#container{
  background-color: gray;
  width: 60%;
  margin: auto;
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  grid-gap: .25em;
}

img{
  width: 100%;
}
<div id='container'>
  <img src='http://www.wallpapereast.com/static/images/MTM3NjEyNzY4MzgyNTU5NDc0.jpg'>
  <img src='http://www.wallpapereast.com/static/images/MTM3NjEyNzY4MzgyNTU5NDc0.jpg'>
  <img src='http://www.wallpapereast.com/static/images/MTM3NjEyNzY4MzgyNTU5NDc0.jpg'>
  <img src='http://www.wallpapereast.com/static/images/MTM3NjEyNzY4MzgyNTU5NDc0.jpg'>
  <img src='http://www.wallpapereast.com/static/images/MTM3NjEyNzY4MzgyNTU5NDc0.jpg'>
</div><!--</container>-->
Ilya Streltsyn
  • 13,076
  • 2
  • 37
  • 57
  • OMG your my new Hero @Ilya Streltsyn xp lol thank you very very much that's what I was looking for. –  Jul 13 '18 at 08:57
  • Its great idea to make this type of style but unfortunately it's not supported in Internet explorer... – Rohit Verma Jul 14 '18 at 04:58
  • Months later I realize this does not work in IE. Is there another alternative method for this kind of behavior @llya Streltsyn? I want to have this similar effect for internet explorer as well. –  Oct 13 '18 at 21:31