如何选择具有特定类别的元素?


79

我的理解是,使用element.class应该允许分配给类的特定元素接收与该类其余部分不同的“样式”。这不是关于是否应该使用它的问题,而是我正在尝试了解此选择器是如何工作的。通过查看互联网上的大量示例,我相信语法是正确的,并且不明白为什么它不起作用。

这是一个例子:

CSS:

h2 {
    color: red;
}

.myClass {
    color: green;
}

h2.myClass {
    color: blue;
}

HTML:

<h2>This header should be RED to match the h2 element selector</h2>
<div class="myClass">
    <h1>This header should be GREEN to match the class selector</h1>
    <h2>This header should be BLUE to match the element.class selector</h2>
</div>

4
可能值得更新问题标题,以反映您实际上是在询问element.class选择器的工作方式,而不是为什么它们没有按您期望的方式工作。
加百利

Answers:


105

应该是这样的:

h2.myClass在class上寻找h2 myClass。但是您实际上想在内部为h2应用样式,.myClass以便可以使用后代选择器.myClass h2

h2 {
    color: red;
}

.myClass {
    color: green;
}

.myClass h2 {
    color: blue;
}

演示版

参考将为您提供有关选择器的一些基本概念,并介绍后代选择器


为了清楚起见,我试图理解element.class选择器的工作方式。我专门尝试使用element.class语法将元素的颜色(位于myClass中的h2)覆盖为蓝色,而不是绿色的类颜色。我想知道如何针对一个类下的特定元素。
卡罗琳

@Carolyn如果需要的话,则需要在h2上使用myClass。像这样jsfiddle.net/wDmwE。原因是h2上的css规则将覆盖容器上的类.myClass。
PSL 2013年

1
太棒了!是的,您的回答确实有帮助。我想我的问题是特异性(我只是在学习这一点)。再次感谢!。非常感激。
卡罗琳

1
最后。我一直在寻找这种解决方案很长时间。我知道elementWithAClass.Class {},但不知道.Class elementInsideThisClass {}。谢谢。我欠你啤酒:D
kv1dr 2014年

57

h2.myClass指的是所有h2class="myClass"

.myClass h2指的是所有h2元素(即嵌套在其中)的子元素class="myClass"

如果希望h2HTML中的变成蓝色,请将CSS更改为以下内容:

.myClass h2 {
    color: blue;
}

如果您希望能够h2通过类而不是其标签来引用它,则应保留CSS并h2在HTML中提供一个类:

<h2 class="myClass">This header should be BLUE to match the element.class selector</h2>

谢谢-我实际上是在试图了解如何使用element.class选择器。我想要“ myClass”下的所有h2元素
Carolyn

@Carolyn,我的最新答案有帮助吗?如果不是,那么我不清楚您的要求。
ASGM 2013年

是的,谢谢!!我仍在努力围绕特异性。
卡罗琳

@Carolyn您有什么特别麻烦的地方吗?
ASGM 2013年

ASGM-我在理解element.class选择器的工作方式时遇到了麻烦。自发布以来,我已经学到了更多(以及本网站上提供的信息),所以我没有正确使用它们。谢谢,
卡罗琳

12

element.class选择器用于如下样式设置:

<span class="large"> </span>
<p class="large"> </p>

.large {
    font-size:150%; font-weight:bold;
}

p.large {
    color:blue;
}

您的span和p都将从.large分配字体大小和字体粗细,但是蓝色仅分配给p。

正如其他人指出的那样,您正在使用的是后代选择器。


谢谢。非常。每个人都非常有帮助。
卡罗琳

2

h2.myClass仅对直接分配h2了类的元素有效myClass

您想这样记录:

.myClass h2

选择所有myClass具有标记名的子代h2


1

CSS:first-child选择器允许您定位作为父元素中第一个子元素的元素。

element:first-child { style_properties }
table:first-child { style_properties }
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.