Casia Hospi Casia Hospi - 4 months ago 6
CSS Question

Image gallery displaying weird after specific elements

I have a simple image gallery made out from an ordered list. The problem with the images is that they aren't equal sizes and the 4th one, respectively the 7th break the flow and they get displayed strangely.

I could fix this with using

#wrapper li:nth-child(5n)
{

clear: left;
}

#wrapper li:nth-child(7n)
{

clear: left;
}


but it be very difficult to maintain if I will add more photos to the gallery. What would be a better solution for the images to display without the elements going out of the normal flow? Thank you!

Answer

Style the li tags for position, not the images within them...

#wrapper ol li {
    float: left;
    display: inline-block;
      width: 50%;
}

Then you can target the odd li items and clear the left floats....

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

Updated Fiddle

Of coarse, this works with two images per row... if you have rows of 3 or more images, then the nth-child will need to be adjusted. (See here)

Comments