Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

css

How to remove margin from every <li> of last column? I'm asking for every <li> which comes in last column when I have 9 <li> and 3 in each column. I'm not asking just to remove margin from last item of last <li> of a <ul> which I already know :last-child { margin-right: 0 }

And if screen is small or user resize the browser then 3 + 3 + 3 can become to 4 + 5 or 2 + 2 + 2 + 2 + 1

So in any condition any <li> ( it can be one or more then one) which comes in last column. I want to remove margin-right.

All li are within a single ul

<ul>
   <li>item 1</li>
   <li>item 2</li>
   <li>item 3</li>
   <li>item 4</li>
   <li>item 5</li>
   <li>item 6</li>
   <li>item 7</li>
   <li>item 8</li>
   <li>item 9</li>
</ul>

I added jsfiddle here: http://jsfiddle.net/GnUjA/1/

like image 463
Jitendra Vyas Avatar asked Sep 24 '11 15:09

Jitendra Vyas


1 Answers

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. */
like image 108
cimmanon Avatar answered Nov 16 '22 00:11

cimmanon