Search code examples
cssalignmentmultiple-columns

css - resize the gap or image based on container width


I am trying to create a simple responsive image gallery with the default number of columns of 3. As the window width gets smaller, the number of columns should decrease as well (first to 2 and finally to 1).

The existing code works ok, but the moment the images get realigned to have 2 columns, they are aligned to the left, leaving an ugly space on the right hand side of the #container.

How would I dynamically increase the gap between the images so the images are still stretched across the #container keeping everything horizontally symmetrical within the #container? Could anyone help me with it.

I have tried a few obvious candidates (eg. #gallery img {align: center} but none of them worked.

The solution/hint could be css/sass and/or js.

<div id="container">
  <header><h1>My Gallery</h1></header>
  <div id="filter"></div>
  <div id="gallery">
        <img src="http://lorempixel.com/400/200/" alt="Gal" />
        <img src="http://lorempixel.com/400/200/" alt="Gal" />
        <img src="http://lorempixel.com/400/200/" alt="ggg" />
        <img src="http://lorempixel.com/400/200/" alt="gog" />
        <img src="http://lorempixel.com/400/200/" alt="Gallery" />
        <img src="http://lorempixel.com/400/200/" alt="Gallery" />
</div> <!-- end of gallery-->
</div> <!-- end of container -->

CSS:

#container {
  width: 70%;
  margin: 0 auto;
  background-color: gray;
  }

Solution

  • Simply add this code to CSS section

    #gallery{ text-align: center;}