tags:

views:

39

answers:

5

I have a parent div, that holds three div's. They are basically columns. I need to remove the margin on the last one but can't get the right selector HTML:

<div class="productContainer">
    <div class="productBox"></div>
    <div class="productBox"></div>
    <div class="productBox"></div>
 <!--/ productContainer --></div>

Here's the CSS:

.productContainer {
    width: 980px;
    height: 400px;
    display: block;
    float: left;
}

How do you target the third child div of a parent? this should work no?
.productContainer > .productBox {
    width: 320px;
    height: 400px;
    display: block;
    float: left;
    margin: 0 10px 0 0;
}

.produtContainer > .productBox nth:child(3) {
    margin-right: 0;
}
A: 

You can do :first-child or :last child to target the first and last element.

compatibility: http://www.quirksmode.org/css/contents.html

Bradley Herman
A: 

You can use :last-child selector for the rule

.productContainer div:last-child
{
    // rule
}

http://www.quirksmode.org/css/firstchild.html

Robert
I'm pretty sure this looks for the last .productContainer, not the last div within it. See my answer.
idrumgood
Has this answer been edited since @idrumgood's comment?
David Thomas
+1  A: 
.productContainter div:last-child
idrumgood
While being aware that this -`:last-child`- isn't available to IE < 9.
David Thomas
why doesn't .productContainer div:nth-child(3) work the same way? Due to IE i might have to just add a class to the last one.
Dirty Bird Design
A: 

You can use the last-child pseudo-selector in this case...

.productContainer > .productBox:last-child {
  margin-right: 0;
}

Note: This will not work in IE8 and older, as this is a part of CSS3. For something more portable, you might want to try this...

<div class="productBox last"></div>

.productContainer > .productBox.last {
  margin-right: 0;
}
Josh Stodola
+1  A: 

While you can use the :last-child selector, it's not going to work in any version of IE before 8. Generally what I do in this situation is add a last class to the last element in the list:

<div class="productContainer">
<div class="productBox"></div>
<div class="productBox"></div>
<div class="productBox last"></div>

And then add this rule below the .productContainer .productBox rule in the stylesheet:

.produtContainer .last {
margin-right: 0;
}
mikeocool
Yeah, I agree I still have to code for IE 7 so I have to do it this way. too bad. thx man.
Dirty Bird Design
It's funny that you said the same thing I did, except five minutes after me. But you get credit for the answer :P
Josh Stodola