htmlcssfrontendresponsiveness

CSS: How to add a margin to each middle element in a list?


I have a dynamic list of <li> elements. The list should display 3 items, designed like cards per row, and then wrap to the next row. There should be spacing between cards (margin). But the first card in the row should not have spacing from the left, and the last card in the row should not have spacing from the right.

So this is what I want (cards on the sides are touching the boundaries of the list): enter image description here

And this is what I want to avoid (spacing between the cards and sides of the list): enter image description here

And ideally, it should be responsive, so on the smaller screen I have 2 cards per row, and then 1 card per row.

So right now my code looks like this:

  ul{
        display: flex;
        flex-wrap: wrap;
        
    }
    li {
        width: 33.3%;
        padding: 15px 15px;
    }

I can't use flex with <li>, and just give it justify-content: space-between; because it might happen that there will be only 2 items in the list and I don't want them to jump to the opposite sides of the page.

I tried to use li:nth-child(2n) to give padding to every even card. But because I specified for each card width: 33.3%; (so it would take 1/3 of the available page width), padding compresses the middle card and makes it narrower.

ul{
    display: flex;
    flex-wrap: wrap;
    
}
li {
    width: 33.3%;
    padding: 15px 0px;
}

/*
li:nth-child(2n){
    width: 33.3%;
    padding: 15px 30px;
}

Also, I soon realized that this was the wrong approach, since I needed to margin every middle card (2, 5, 8, 11, etc), not every even card.

What would you suggest?


Solution

  • Use gap, e.g.:

    ul {
        display: flex;
        flex-wrap: wrap;
        gap: 20px;        
    }
    

    gap basically puts a gap BETWEEN elements. Hence, no padding/spacing will be added above/below or to the left/right unless there is a neighbor item.

    If you only need a gap between columns use column-gap or row-gap if only between rows.