0
<div id="wrapper">
     <div class="top-tab">
         <div class="top-tab-box"></div>
         <div class="top-tab-box"></div>
         <div class="top-tab-box"></div>
         <div class="clear"></div>
        </div>
    </div>

<style>
.top-tab-box
{
   width: 200px;
   height: 200px;
   background: #000;
   float: left;
   margin: 10px;

}
.top-tab div.top-tab-box:last-child{
   background: #e7e7e7;
}
</style>

I have this html code.if I removed

<div class="clear"></div>

then last-child worked

but with this clear div last-child property not working

web-tiki
  • 99,765
  • 32
  • 217
  • 249
Ankit Agrawal
  • 6,034
  • 6
  • 25
  • 49

3 Answers3

1

When the clearing div is not present, the tab-box div is the last-child, but not otherwise. (At the moment, the clearing div is the last child, so your rule can't apply to the last tab-box.) Try giving your #wrapper overflow: hidden; instead of using the clearing div.

ralph.m
  • 13,468
  • 3
  • 23
  • 30
1

That's because <div class="clear"></div> is the actual :last-child

I suggest you to use ':last-of-type' instead of :last-child and don't use a <div> for the clearing.

Try this

<div id="wrapper">
     <div class="top-tab">
         <div class="top-tab-box"></div>
         <div class="top-tab-box"></div>
         <div class="top-tab-box"></div>
         <!-- don't use a div for .clear-->
<span class="clear"></span>
    </div>

and css

.top-tab div:last-of-type{
   background: #e7e7e7;
}

Also remember to change the .clear selector in css to something like .clear {clear:both;display:block;} if you are going to use `'

**

Check this fiddle http://jsfiddle.net/4psdN/

**

Frondor
  • 3,466
  • 33
  • 45
  • I just edited my post with additional information about using span as clearing element, and added a jsfiddle that should guide you. Maybe you didn't see it yet :) – Frondor Jun 17 '14 at 10:06
1

You could use nth-last-child(2) to select the second-last element of the div: http://jsfiddle.net/JX58w/

#wrapper div div:nth-last-child(2){
   background: red;
}
Niek Vandael
  • 394
  • 1
  • 3
  • 15