2014-09-04 58 views
0

在以下标记中,我想申请CSS只有与类.box,其中紧跟在.wrap之后。如果它在<p>.wrap以外的任何其他类之后,我不想选择它。选择第一课后,在一个特定的类

<div class="wrap"> 
    <div class="box">Apply style to this box</div> 
    <p>random</p> 
    <div class="box">Do not apply style to this box</div> 
</div> 

我试图看看邻接的兄弟选择器,但似乎并没有在这种情况下工作。

.wrap + .box{ 
    background: red; 
} 

的jsfiddle:http://jsfiddle.net/8fjuz7sm/

我不能使用:first-child,因为它只能出现一次了。

回答

1

写:

.wrap .box:first-of-type{ 
    background:red; 
} 

DEMO here

OR

.wrap .box:nth-of-type(1){ 
    background:red; 
} 

DEMO here

0

作为@Hiral说,你必须使用first-of-typenth-of-type(1)

如果你不能做到这一点,但可以访问HTML,你就必须到其他类添加到您希望应用类上的元素,如

<div class="wrap"> 
<div class="box red">Apply style to this box</div> 
<p>random</p> 
<div class="box">Do not apply style to this box</div> 
</div> 

,或者您可以使用JavaScript和/或jquery选择第一个元素,然后通过javascript应用样式。

  • jQuery的实例

$(".wrap .box").eq(0).css("Background-color","red")

0

我编辑您的jsfiddle:http://jsfiddle.net/8fjuz7sm/4/

我建议使用jQuery这是因为旧的浏览器可能不支持纯CSS解决方案:

创建一个新班级:

.wrapperbox { 
    background: red; 
} 

那么这个jQuery代码添加到您的脚本:与类包裹其中有一个孩子箱将获得一类wrapperbox

$(".wrap > .box:first").addClass("wrapperbox"); 

在此之后所有的HTML元素,在那里,你可以做你的CSS

当你不想做的jQuery,你可以使用这个:

.wrap .box:first-of-type{ 
    background:red; 
} 

这将选择包的第一个孩子与类名框中,然后做哟你的css

相关问题