2013-09-27 274 views
3

我试图选择第.box类中的第一个元素,但不包括类.topbar中的类。选择第一个元素,但排除在其他元素内部的元素

我用这种方法:not(.topbar)>.box,并且选择内部.topbar所有元素.box排除一个,但我只是想第一个。

我知道我可以在一个更简单的方法选择,但我不知道我怎么能这样做的......

注:元素的数目是不固定的,所以.topbar可能存在或不...

例子:

<body> 
    <div class="topbar"> 
     <div class="box"> 
      ... 
     </div> 
    </div> 
    <div class="box"> <!-- Just want to select this one --> 
     ... 
    </div> 
    <div class="box"> 
     .... 
    </div> 
</body> 

谢谢!

+0

是所有的div.box元素总是直接的身体的孩子(除了在顶部的一个),或者他们可以在DOM中的任何地方? – andi

+0

正确,所有身体的直接孩子 – isramartinez

+0

伙计我想'body> .box:first-child {border:1px solid red; }'很好,但这似乎不起作用,为什么? [jsfiddle](http://jsfiddle.net/S5Efg/) –

回答

3

我想你可以把这个分成两种情况: 1)就像你上面的例子,顶栏是第一个孩子,盒子是老二 2)如果顶栏不存在,那么箱是第一个孩子

.topbar + .box, body > .box:first-child {background:red;} 
+0

我以为'body> .box:first-child'会起作用,但不知何故它不会。你的答案似乎是解决方案。 – LinkinTED

+0

@andi该解决方案效果很好,谢谢! – isramartinez

1
.topbar + .box { background:red; } 
+0

这是一个完美的工作,但不存在'.topbar'时不存在。与此同时,你给我的答案是我正在编辑我的问题,以添加“.topbar”不能存在的注释。 – isramartinez

2

这是一个更强大的方法。

考虑原始的HTML代码段的更广义的版本:

<div class="topbar"> 
    <div class="box">In the topbar...</div> 
    <div class="box">In the topbar...</div> 
</div> 
<div>temp</div> 
<div class="box">Just want to select this one...</div> 
<div class="box">a second one....</div> 
<div>temp</div> 
<div class="box">a third one....</div> 
<div>temp</div> 
<div class="box">a third one....</div> 

,并应用以下CSS:

body > div.box 
{ 
    background-color: beige; 
} 
body > div.box ~ div.box 
{ 
    background-color: pink; 
} 

见演示在:http://jsfiddle.net/audetwebdesign/Rufcc/

第一条规则选择所有div.box元素是body的子元素,并应用背景颜色。

第二条规则然后选择第一个元素后面的所有div.box元素,然后将背景颜色覆盖为某个默认值(可能为transparent)。

这种方法的主要优点是它可以挑选出第一个div.box元素,而不管之前有多少其他元素。

+0

div.box与div.box:nth-of-type(n)相同 – andi

+0

你是对的!我专注于别的东西... –

+0

不错的广义版本,但。 – andi

相关问题