3

This is one of the common issues i face and i end up having nasty additional spacer markup to avoid having a margin in the right or the left ( also at the top or the bottom if it's a vertical menu ).

Is there a clean css way to avoid applying the margin for the last element?


enter image description here

CodeOverload
  • 47,274
  • 54
  • 131
  • 219
  • 2
    This irks me no end as well. I usually end up adding a `.last` class to the last item. You could also see about using `last-child`, should be supported on modern browsers though : http://stackoverflow.com/questions/1293369/using-last-child-in-css – JohnP Jun 26 '11 at 14:45

4 Answers4

6

Use :not(:last-child).

.box:not(:last-child) {
    margin-right: 10px;
}

Or,

.box:not(:first-child) {
    margin-left: 5px;
}

.box:not(:last-child) {
    margin-right: 5px;
}

Or,

.box {
    margin-right: 10px;
}
.box:last-child {
    margin-right: 0px;
}

Or,

.box {
    margin: 0 5px;
}

.box:first-child {
    margin-left: 0;
}

.box:last-child {
    margin-right: 0;
}

Compatibility:

Matt Ball
  • 354,903
  • 100
  • 647
  • 710
  • Thanks that looks clean, The real question is: is it supported by major browsers? Thanks again. – CodeOverload Jun 26 '11 at 14:45
  • @David which versions of IE do you care about? – Matt Ball Jun 26 '11 at 14:46
  • @Harpyon, that will require another selector for `.box` using the `not()` means only using one. Although if other CSS properties are being set it would be more efficient to drop the `not()`. – Jonathan. Jun 26 '11 at 14:52
  • It's funny, you posted almost every variation except the one that should actually be used (thanks to IE7/8). Still, +1 – thirtydot Jun 26 '11 at 14:59
2

You should use:

.box {
    margin-left: 20px
}
.box:first-child {
    margin-left: 0
}

This is better than using :last-child (from CSS 3), because that's not supported in IE7/8, whereas :first-child (from CSS 2) is.

thirtydot
  • 224,678
  • 48
  • 389
  • 349
1

i guess you can try this one, http://jsfiddle.net/yuliantoadi/g98Wq/

html :

<div class="container">
<div class="box">
    box 1
</div>
<div class="box">
    box 2
</div>
<div class="box">
    box 3
</div>
    <div style="clear:both"></div>
</div>

css:

.box{
    width:32%;
    float:left;
    background:red;
    margin-left:2%;
}
.container {
    background:blue;
    padding:2%;
}
.container .box:first-child{
    margin-left:0;
}

is that what you mean?

yoel
  • 409
  • 4
  • 9
0

According to Quirks Mode :last-child isn't supported in IE6/7/8 so an alternative could be to apply another class to the last element and then just override the margin in the CSS.

Steve Day
  • 417
  • 4
  • 14