我有HTML这样的:的DIV insde第一类元素的CSS选择器
<tag1>
<div class="c"> // need to select that
<tag1>
<div class="c"> // do not need that
</div>
</tag1>
</div>
</tag1>
我要选择的第一tag1
内div
应用CSS规则
我试图tag1:first-of-type c {}
,但它没”工作。
我有HTML这样的:的DIV insde第一类元素的CSS选择器
<tag1>
<div class="c"> // need to select that
<tag1>
<div class="c"> // do not need that
</div>
</tag1>
</div>
</tag1>
我要选择的第一tag1
内div
应用CSS规则
我试图tag1:first-of-type c {}
,但它没”工作。
如果您想选择你的标签内都类,你只需要一个.
在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>
希望这有助于! :)
我只需要选择'外部'一个不需要'内部' – sreginogemoh
用你当前的结构做这件事是不可能的(假设**完全**你的结构,没有额外的ID或类名)。您必须按照您希望外部线段进行样式设计的方式对两个线段进行**设置,然后将内部线段设置回“默认”状态。 –
什么是解决这个问题的最佳方式,而不需要接触html结构? – sreginogemoh
您不能可能做到这一点在CSS - 你将不得不破解通过自己的方式,如果你不能改变你的标记。
设置使用tag1 .c:first-of-type
使用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>
你的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 { }
不以这种方式工作 – sreginogemoh
@sreginogemoh:只有可能的原因,这不能工作是如果你的外部tag1不是身体的孩子。显然你需要调整选择器来处理你的实际标记。 – BoltClock
这是相当简单的。你只需要两条规则。
的第一条规则将选择你需要的东西:
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>
'TAG1 .C:首个,type'? – kukkuz