2

JS Fiddle

Without altering the html is there any way to target the last .red class using CSS?

<div class="row">
    <div class="red">Red</div>
    <div class="red">Red</div>
    <div class="red">Target Me With CSS???</div>
    <div class="blue">Blue</div>
    <div class="blue">Blue</div>
    <div class="blue">Blue</div>
</div>

here's what I've tried :

.row > div{
    display:inline-block;
    padding:10px;
}

.row .red{
    background-color:#770000;    
    color:#fff;
}

.row .red:first-child{
    background-color:#440000;    
    color:#fff;
}

/*have tried :last-of-type too*/
.row .red:last-child{
    background-color:#FF0000;    
}

.row div:last-child{
    background-color:#0000BB;    
}
Rob
  • 10,004
  • 5
  • 61
  • 91

3 Answers3

1

I don't believe there is a way to do that without using JS.

The closest you can get is to target the 3rd item with:

.row div:nth-child(3) {
    background: chucknorris;
}

You can include a qualifier to only target the third child if it is .red like so:

.red:nth-child(3) {  
   background: chucknorris; 
}

http://jsfiddle.net/s76J3/3/

Mark Simpson
  • 2,344
  • 2
  • 23
  • 31
1

Unfortunately, you can't do this with CSS alone. Here are a few other SO questions that are related to yours:

However, if your last .red sometimes is in different positions, and you can't change the HTML at all, then you will have to rely on some light JS/jQuery.

$(function() {
    $('.row .red').last().addClass('last-red-class');
});

You can use it to add another class to the last .red, and just reference that in your CSS.

http://jsfiddle.net/s76J3/2/

HTH

Community
  • 1
  • 1
Ming
  • 4,468
  • 1
  • 21
  • 21
0

:last-of-type description

The :last-of-type CSS pseudo-class represents the last sibling of its type in the list of children of its parent element.

and syntax

element:last-of-type { style properties }

So, what really going in your example is that the browser selected the right div element but it was not the last div element of its parent; therefore, nothing was applied. To test this, change all your .red class div into a span and do the following

.row span:last-of-type{
    background-color:#FF0000;    
}

then you will get a working code.

http://jsfiddle.net/s76J3/4/

Source: https://developer.mozilla.org/en-US/docs/Web/CSS/:last-of-type

Infinity
  • 3,695
  • 2
  • 27
  • 35