[英]Css Selector for elements with a specific class and parent
I want to style an element if it has a specific class and parent element. 如果元素具有特定的类和父元素,我想为其设置样式。 If i use
caption > h1
it works perfectly, but a soon as I add my class .sub
it doesn't work anymore. 如果我使用
caption > h1
则可以正常运行,但是一旦添加我的class .sub
它就不再起作用。
HTML: HTML:
<caption>
<h1 class="sub">Text</h1>
</caption>
CSS: CSS:
works: 作品:
caption > h1 {
font-weight: 500;
color: #777;
font-family: sans-serif;
}
doesn't work: 不起作用:
.sub caption > h1 {
font-weight: 500;
color: #777;
font-family: sans-serif;
}
How is it possible to select elements with a specific parent
and class
? 如何选择具有特定
parent
class
和class
元素?
The >
selector indicates a direct parent. >
选择器表示直接父代。 Your above code .sub caption > h1
is attempting to select any h1
element that is a direct child of a caption
element, where the <caption>
element is a child of an element with the class .sub
. 您上面的代码
.sub caption > h1
试图选择任何caption
元素的直接子元素的h1
元素,其中<caption>
元素是.sub
类的元素的子元素。 It is not working because you don't have a parent of <caption>
with the class of sub
. 它不起作用,因为您没有
sub
类的<caption>
父级。
You can specify that your target elements must contain specific classes by writing the element selector immediately followed by the class selector (without a space). 您可以通过在紧随其后的类选择器(无空格)之后编写元素选择器来指定目标元素必须包含特定的类。 For example,
h1.sub
targets any <h1>
element that has the class sub
. 例如,
h1.sub
定位到具有sub
类的任何<h1>
元素。 It won't target <h1>
elements that don't have the .sub
class, nor elements that are not <h1>
elements but do have the .sub
class. 它不会靶向
<h1>
不具有元素.sub
类, 也不是说不是元素<h1>
元素,但确有.sub
类。
It's also important to note that <caption>
is only valid as a direct child of <table>
. 还需要注意的是,
<caption>
仅作为<table>
的直接子代才有效 。
Essentially, what you're looking for is the following: 本质上,您要查找的是以下内容:
caption > h1.sub { color: red; }
<table> <caption> <h1 class="sub">Text</h1> </caption> </table>
This targets any <h1>
element with the class of .sub
that is a direct child of <caption>
. 这将以
.sub
类为<caption>
的直接子级的任何<h1>
元素为目标。
Hope this helps! 希望这可以帮助! :)
:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.