Search code examples
cssimagecss-floatfigure

Floated images in Image Gallery Have Spacing Issues


I am trying to use the float property to create a page that looks like a two-column image gallery. It’s almost there, but there are awkward spaces within columns that I don’t know how to eliminate. Does the solution involve clearing some of the floats?

Screenshot of the issue:

Screenshot

Code:

#image-gallery figure {
  text-align: center;
  font-family: 'Alegreya Sans', sans-serif;
}
figure img {
  margin-top: 10px;
  margin-left: auto;
  margin-right: auto;
  width: 100%;
  border: 3px solid purple;
  box-sizing: border-box;
}
#image-gallery {
  margin: 0;
  padding: 0;
  list-style: none;
}
@media screen and (min-width: 500px) {
  #image-gallery img {
    width: 45%;
  }
  #image-gallery li {
    float: left;
    width: 45%;
    margin: 2.5%;
  }
}
<section>
  <div>
    <ul id="image-gallery">
      <li>
        <figure>
          <img src="street-art-banksy.jpg" alt='missing' />
          <figcaption><a href="street-art-banksy.jpg">Street Art | Banksy</a>`</figcaption>`
        </figure>
      </li>

      <li>
        <figure>
          <img src="SoulForSale.jpg" alt="missing" />
          <figcaption><a href="SoulForSale.jpg">Soul For Sale | Bosoletti</a>`</figcaption>`
        </figure>
      </li>

      <li>
        <figure>
          <img src="ColorRain.jpg" alt="missing" />
          <figcaption><a href="ColorRain.jpg">Color Rain | Chris Wiedmann</a>`</figcaption>`
        </figure>
      </li>

      <li>
        <figure>
          <img src="NataliaRak.jpg" alt="missing" />
          <figcaption><a href="NataliaRak.jpg">Mural | Natalia Rak</a>`</figcaption>`
        </figure>
      </li>

      <li>
        <figure>
          <img src="Jetsonoroma-Lola.jpg" alt="missing" />
          <figcaption><a href="Jetsonoroma-Lola.jpg">Lola | Jetsonoroma</a>`</figcaption>`
        </figure>
      </li>

      <li>
        <figure>
          <img src="JoeCaslin-TheCastle.jpg" alt="missing" />
          <figcaption><a href="JoeCaslin-TheCastle.jpg">The Castle | Joe Caslin</a>
          </figcaption>
        </figure>
      </li>

      <li>
        <figure>
          <img src="RenaissanceMasters-OwenDippie.jpg" alt="missing" />
          <figcaption><a href="RenaissanceMasters-OwenDippie.jpg">Michelangelo, Raphael, Donatello, and Leonardo | Owen Dippie</a>
          </figcaption>
        </figure>
      </li>

      <li>
        <figure>
          <img src="VariousAndGold-Facetime.jpg" alt="missing" />
          <figcaption><a href="VariousAndGold-Facetime.jpg">Facetime | Various and Gold</a>
          </figcaption>
        </figure>
      </li>
    </ul>
  </div>
</section>


Solution

  • You can use a css clear on all the odd children.

    li:nth-child(odd) {
        clear: left;
    }
    

    Checkout the following articles to learn more about float and clear.