2017-08-28 69 views
1

我有HTML这样的:的DIV insde第一类元素的CSS选择器

<tag1> 
<div class="c"> // need to select that 
    <tag1> 
    <div class="c"> // do not need that 
    </div> 
    </tag1> 
</div> 
</tag1> 

我要选择的第一tag1div应用CSS规则

我试图tag1:first-of-type c {},但它没”工作。

+0

'TAG1 .C:首个,type'? – kukkuz

回答

1

如果您想选择你的标签内都类,你只需要一个.在C面前:

tag1:first-of-type .c { 
 
    color: red; 
 
}
<tag1> 
 
<div class="c">Outer 
 
    <tag1> 
 
    <div class="c">Inner 
 
    </div> 
 
    </tag1> 
 
</div> 
 
</tag1>

值得注意的是,它实际上是不可能的风格的外部元素与您的上述结构,虽然你总是可以解决这个问题,通过更大的风格分别内部元素specificity

tag1:first-of-type > .c { 
 
    color: red; 
 
} 
 

 
tag1:first-of-type tag1 .c { 
 
    color: black; 
 
}
<tag1> 
 
<div class="c">Outer 
 
    <tag1> 
 
    <div class="c">Inner 
 
    </div> 
 
    </tag1> 
 
</div> 
 
</tag1>

希望这有助于! :)

+0

我只需要选择'外部'一个不需要'内部' – sreginogemoh

+0

用你当前的结构做这件事是不可能的(假设**完全**你的结构,没有额外的ID或类名)。您必须按照您希望外部线段进行样式设计的方式对两个线段进行**设置,然后将内部线段设置回“默认”状态。 –

+0

什么是解决这个问题的最佳方式,而不需要接触html结构? – sreginogemoh

0

不能可能做到这一点在CSS - 你将不得不破解通过自己的方式,如果你不能改变你的标记。

  1. 设置使用tag1 .c:first-of-type

  2. 使用tag1 tag1 .c:first-of-type选择和<property>: initial复位tag1风格。

请参见下面的演示:

tag1 .c:first-of-type { 
 
    color: red; 
 
} 
 

 
tag1 tag1 .c:first-of-type { 
 
    color: initial; 
 
}
<tag1> 
 
<div class="c">1 
 
    <tag1> 
 
    <div class="c">2 
 
    </div> 
 
    </tag1> 
 
</div> 
 
</tag1>

0

你的HTML propably将由其他标签包围,例如body标签。只针对外部股利,只是更具体。

<body> 
<tag1> 
<div class="c"> // need to select that 
    <tag1> 
    <div class="c"> // do not need that 
    </div> 
    </tag1> 
</div> 
</tag1> 
</body> 

CSS

body > tag1 > div.c { } 
+0

不以这种方式工作 – sreginogemoh

+0

@sreginogemoh:只有可能的原因,这不能工作是如果你的外部tag1不是身体的孩子。显然你需要调整选择器来处理你的实际标记。 – BoltClock

0

这是相当简单的。你只需要两条规则。

的第一条规则将选择你需要的东西:

aside > .c { 
color: rgb(255, 0, 0); 
font-weight: bold; 
} 

第二条规则将设置普通样式,并同时取消符合该模式aside > .c任何元素,但其嵌套比第一aside任何更深:

.c, aside aside > .c { 
color: rgb(0, 0, 0); 
font-weight: normal; 
} 

工作实施例:

aside { 
 
display: inline-block; 
 
width: 50%; 
 
height: 25%; 
 
padding: 12px; 
 
border: 2px solid rgb(0, 0, 0); 
 
} 
 

 
aside > .c { 
 
color: rgb(255, 0, 0); 
 
font-weight: bold; 
 
} 
 

 
.c, aside aside > .c { 
 
color: rgb(0, 0, 0); 
 
font-weight: normal; 
 
}
<aside> 
 
<div class="c"> // need to select this 
 

 
<aside> 
 
<div class="c"> // do not need that </div> 
 
</aside> 
 

 
</div> 
 
</aside>