styler
styler

Reputation: 16501

How to add a consistent margin to each thumbnail grid item without breaking % grid?

I've drawn a bit of a blank when creating a thumbnail grid, I want to add add 20px margin to each grid item in my 3 column grid making sure the first and last of each row sit flush with the container. Each grid item has a width of 33.33334% so when I add margin-right: 20px; to each then the grid breaks. As I say, I'm drawing a blank on how to do this keeping the grid consistent, each grid item the same width but with a margin after the first and second items?

CSS

.grid-item {
    flex: 1 0 33.3334%;
    margin-right: 20px;
    &:nth-child(3n+n) {
        margin-right: 0;
    }
    .grid-inner {
        padding: 20px;
    }
    img {
        max-width: 100%;
    }
}

Demo: http://codepen.io/styler/pen/xzogr

Upvotes: 0

Views: 174

Answers (2)

andi
andi

Reputation: 6522

How about percentage based margins, to keep the numbers perfect? This has each grid item at 32% (total 96% for 3 of them) and then a 2% margin on the left and right side of the center item.

.grid-item {
   flex: 1 0 32%;

   &:nth-child(3n+2) {
     margin:0 2%;
   }

   .grid-inner {
   }

Upvotes: 1

gilbert-v
gilbert-v

Reputation: 1305

I think the easiest and most robust solution would simply be to use a <table>.

You could feature this CSS instead:

td {
    max-width: 800px;
    margin: auto;
    display: inline-block;
    align-content: center;
}

img {
    max-width: 100%;
    padding: 10px;
}

This would simplify the math, and the need for flex and flex-wrap etc.

Upvotes: 0

Related Questions