Search code examples
cssgridmargins

CSS grid items with even gutters and a full width grid


I'm working on a layout that contains a grid like layout within it to show off a set of offers. Here's what I'm trying to achieve:

Objective

My problem is I cannot seem to get even and flushed gutters within this grid. Here's what I have so far:

Current Result

HTML:

<div id="main">
    <div><img src="images/welcomeBanner.jpg"></div>
    <div class="offers">
        <img class="offer" src="images/offer1.jpg">
        <img class="offer" src="images/offer2.jpg">
        <img class="offer" src="images/offerX.jpg">
        <img class="offer" src="images/offerX.jpg">
        <img class="offer" src="images/offerX.jpg">
        <img class="offer" src="images/offerX.jpg">
    </div>
</div>

CSS:

div#content div#main div.offers img.offer{ padding-top:20px; padding-right: 20px; }

I am using padding-right:20px; on each of these offer items (img.offer). Since these offers are all inline, I cannot seem to get each row to flush with the right side of this main column (align with the right side of the larger banner with the hands).

I would love to achieve this with pure CSS, but I'm coming to the realization that might not happen. I would try :nth-child(3n), but the lack of IE support is a deal breaker for me.

I have no means of using a server side processor to do some math on the number of grid items. I recognize that I may just want to use javascript or jquery to do this math, but I wanted to reach out to see if anyone had any other suggestions.

TLDR: Help me get even gutters and a full width grid.

Thanks everyone!


Solution

  • I don't know what the width of your container is, but this may help:

    .offer {
        /* some stuff */
        padding-right: 25px; /* You have to find a good value */
    }
    .offer:nth-child(3n) {
        padding-right: 0;
    }
    

    If you don't want to use nth-child() you can alternatively give every 3rd image (.offer) an additional class.