[英]CSS selector for the div insde first of type element
I have HTML like: 我有类似的HTML:
<tag1>
<div class="c"> // need to select that
<tag1>
<div class="c"> // do not need that
</div>
</tag1>
</div>
</tag1>
I want to select the div
inside the first tag1
to apply CSS rule 我想在第一个tag1
选择div
以应用CSS规则
I tried tag1:first-of-type c {}
but it didn't work. 我尝试了tag1:first-of-type c {}
但是没有用。
If you want to select both classes inside your tag, you simply need a .
如果要在标记中选择两个类,则只需一个.
in front of the C: 在C前面:
tag1:first-of-type .c { color: red; }
<tag1> <div class="c">Outer <tag1> <div class="c">Inner </div> </tag1> </div> </tag1>
Of note, it's actually impossible to only style the outer element with your above structure, though you can always get around this by styling the inner element separately with greater 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>
Hope this helps! 希望这可以帮助! :) :)
You can't possibly do that in CSS - you will have to hack your way through if you can't change your markup. 您可能无法在CSS中做到这一点-如果您无法更改标记,则将不得不破解 。
Set the style using tag1 .c:first-of-type
使用tag1 .c:first-of-type
设置样式
Reset the inner tag1
using tag1 tag1 .c:first-of-type
selector and <property>: initial
. 使用tag1 tag1 .c:first-of-type
选择器和<property>: initial
重置 内部 tag1
。
See demo below: 请参见下面的演示:
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>
Your html propably will be surrounded by other tags, for example a body tag. 您的html可能会被其他标签包围,例如body标签。 To only target the outer div, simply be more specific. 要仅定位外部div,只需更加具体。
<body>
<tag1>
<div class="c"> // need to select that
<tag1>
<div class="c"> // do not need that
</div>
</tag1>
</div>
</tag1>
</body>
CSS CSS
body > tag1 > div.c { }
This is fairly straightforward. 这很简单。 You just need two rules. 您只需要两个规则。
The first rule will select what you need: 第一条规则将选择您需要的内容:
aside > .c {
color: rgb(255, 0, 0);
font-weight: bold;
}
The second rule will set the normal styles and simultaneously deselect any element which fits the pattern aside > .c
but which is nested any deeper than the first aside
: 第二条规则将设定的正常方式和同时取消选择符合该图案的任何元件aside > .c
但嵌套比第一任何更深aside
:
.c, aside aside > .c {
color: rgb(0, 0, 0);
font-weight: normal;
}
Working Example: 工作示例:
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.