How to remove margin from every element that is the last element in a row?

Removing or adding stylings on a specific element of each row cannot be done with pure CSS unless you know exactly how many elements there are per row (via the nth-child() family of selectors).

Negative Margins

What you can to do in the case of margins is disguise them by adding negative margins on the parent element. This will give the illusion that your child elements fit inside the parent element while still having spacing between the individual elements:

http://codepen.io/cimmanon/pen/dwbHi

ul {
    margin-left: -5px;
    margin-right: -5px;
}

li {
    margin-left: 5px;
    margin-right: 5px;
}

Splitting the margin in half and setting it on both sides (margin-left: 5px; margin-right: 5px) may give better results than a single margin on one side (margin-right: 10px), particularly if your design needs to work with LRT and RTL directions.

Note: this may require adding overflow-x: hidden on an ancestor element to prevent horizontal scrolling, depending on how close the container element is positioned to the edge of the viewport.

Media Queries

If you can reasonably predict how many items there are going to be per row, you can use media queries to target the last item in the row via nth-child(). This is considerably more verbose than using negative margins, but it would allow you to make other style adjustments:

@media (min-width: 400px) and (max-width: 499px) {
    li:nth-child(even) {
        margin-right: 0;
        border-right: none;
    }
}

@media (min-width: 500px) and (max-width: 599px) {
    li:nth-child(3n+3) {
        margin-right: 0;
        border-right: none;
    }
}

@media (min-width: 600px) and (max-width: 799px) {
    li:nth-child(4n+4) {
        margin-right: 0;
        border-right: none;
    }
}
/* etc. */

Leave a Comment