2013-11-25 33 views
2

JS FiddleCSS靶向最后一个类类型,它是不是最后孩子

在不改变HTML有没有办法为目标的最后.red类使用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> 

这里就是我已经试过:

.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;  
} 

回答

1

我不相信有办法做到这一点,而不使用JS。

你可以得到的最接近的是针对与第3项:

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

可以包括限定只针对第三个孩子如果.red像这样:

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

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

1

不幸的是,你不能单独使用CSS来做到这一点。下面是涉及到你的其他一些做题:

然而,如果你最后.red有时是在不同的位置,并且不能更改在所有的HTML,那么你将不得不依靠一些轻的JS/jQuery。

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

你可以用它到另一个类添加到最后.red,只是引用您的CSS。

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

HTH

+0

这只是对我来说 – bowlerae

0

:浏览器选择的描述

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

和语法最后型-

element:last-of-type { style properties } 

那么,是什么在你的例子真的是正确的div元素,但它不是它的par的最后一个div元素耳鼻喉科;因此,没有应用。要进行测试,更改所有.red类DIV成跨度,请执行下列操作

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

那么你会得到一个工作代码。

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

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

+0

工作,我特别指出了解决方案 - > “在不改变HTML”。 – Rob

相关问题