1

In the following code I want to add styling specifically to the content of the last "B".

<div class="A">
  <div>
   I am <span class="B">foo</span>.
  </div>
  <div>
   I like <span class="B">bars</span>.
  </div>
  <div>
   Actually, call me <span class="B">FOOBAR</span>.
  </div>
</div>

I have been trying

.B:last-of-type { color: red; }

and all classes "B" get selected because it uses the last occurence in it's immediate parents child elements. i.e. in it's direct siblings

Is there any way to only select the last occurence of "B" in the whole document?

collinglass
  • 800
  • 4
  • 11
  • 31

5 Answers5

3

You can do it like this

.A div:last-of-type .B { color: red; }

Fiddle Demo

or

.A div:last-child .B { color: red; }

Fiddle Demo

Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
2

Try this JsFiddle Demo

.A div:last-child .B{ color: red; }
Sachin Jain
  • 21,353
  • 33
  • 103
  • 168
0

Found the answer! CSS3 get last element

I was doing a version of this but I found it ugly, I guess this is the only way. I will keep this Question open for a bit to see if anyone has any better suggestions.

Community
  • 1
  • 1
collinglass
  • 800
  • 4
  • 11
  • 31
0
.A span.B:last-child
{
background:#999;
}
0
.A div:last-child .B:last-child
{
background:orange;
}