0

I am having trouble getting :last-child to work in my situation.

HTML:

<div class="test">Some content</div>
<div class="test">Some content</div>
<div class="test">Some content</div>
<div class="action">Some other content</div>

CSS:

div.topic {
    border-bottom: 1px solid black;
}

div.topic:last-child {
    border-bottom: none;
}

JSFiddle

The last div.test still has the border at the bottom. ​ The problem I think is that the border-bottom: none applies to the very last div which is div.action and not to the last div of class test.

How can I solve it?

Filburt
  • 17,626
  • 12
  • 64
  • 115
Eleeist
  • 6,891
  • 10
  • 50
  • 77
  • 2
    Have a read of this: http://stackoverflow.com/questions/6401268/how-do-i-select-the-last-child-with-a-specific-class-name-in-css your question is,possibly, a duplicate. Short answer there's no `:last-of-class` selector, so you'd need to use JavaScript or use [`border-top`](http://jsfiddle.net/97Dr4/1/). – David Thomas Dec 16 '12 at 17:34
  • The solution to the question you linked to is using absolute orderding (ie. 4th item) while my divs are generated by the server and I don't know how many there are. – Eleeist Dec 16 '12 at 17:37
  • oops, I copied from the wrong tab XD I've edited the original comment, and changed to the link I meant to copy. Sorry for the confusion. – David Thomas Dec 16 '12 at 17:39

2 Answers2

2

You will have to update your markup in order to achieve desired result. Wrap your unknown items in a wrapper, eg:

Working DEMO

<div id="list">
 <div class="topic">Some content</div>
 <div class="topic">Some content</div>
 <div class="topic">Some content</div>
</div>
<div class="action">Some other content</div>​

then use this CSS:

#list .topic {
 border-bottom: 1px solid black;
}

#list .topic:last-child {
 border-bottom: none;
}
Gurpreet Singh
  • 20,907
  • 5
  • 44
  • 60
  • I think I will have to go with this one. I am just surprised that this selector works this way (ie. ignores the class...). – Eleeist Dec 16 '12 at 17:42
0

I'd suggest using first-child, not last-child.

div.topic {
    border-top: 1px solid black;
}

div.topic:first-child {
    border-bottom: none;
}

This works with your current HTML, and is more cross-browser compatible.

Gareth Cornish
  • 4,357
  • 1
  • 19
  • 22
  • more cross-browser compatible than what? `:first-child` is as well supported as `:last-child`. Both don't work in older browsers and IE. – Horen Dec 16 '12 at 17:50
  • @Horen first-child works in IE8, but last-child does not. http://jsfiddle.net/JT5SN/3/. (see http://www.w3schools.com/css/css_pseudo_classes.asp) – Gareth Cornish Dec 16 '12 at 18:06