Preventing "double" borders in CSS

#divNumberOne { border-right: 0; }


If we're talking about elements that cannot be guaranteed to appear in any particular order (maybe 3 elements in one row, followed by a row with 2 elements, etc.), you want something that can be placed on every element in the collection. This solution should cover that:

.collection {
    /* these styles are optional here, you might not need/want them */
    margin-top: -1px;
    margin-left: -1px;
}

.collection .child {
    outline: 1px solid; /* use instead of border */
    margin-top: 1px;
    margin-left: 1px;
}

Note that outline doesn't work in older browsers (IE7 and earlier).

Alternately, you can stick with the borders and use negative margins:

.collection .child {
    margin-top: -1px;
    margin-left: -1px;
}

HTML:

<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>

​CSS:

div {
    border: 1px solid #000;
    float: left;
}

div:nth-child(n+2) {
    margin-left: -1px;
}

Demo

Include ie9.js for IE8 support (it's very useful for all CSS selectors/pseudo-elements).

Tags:

Css