2
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">
<html> <head>
<title>How to Write a Good Report</title>
<style type="text/css">
div.weather strong:first-child {color:red;}
</style>
</head>

<body>

<div class="weather">
It's <strong>very</strong> hot and <strong>incredibly</strong> humid.
</div>

</body> </html>

为什么只有“非常”是红色,而“难以置信”不是,因为它们都是“div.weather strong”指定元素的第一个子元素?

4

6 回答 6

6

因为 psuedo-selector 并没有做你认为它做的事情。

.weather在您陈述的示例中,它选择元素的第一个子<strong>元素。

所以只有第一个实例匹配。我无法参考规范来支持这一点,因为我现在很懒(忙碌的一天......),但我脑子里有这样的愿景:

<html>

<div class="weather">

<p><strong>Lorem</strong> ipsum <strong>sit</strong> <em>amet</em> <span><a...>dolor</a><em>yadda yadda yadda</em></span> <a>something</a>, I'm not good at coming up with random text. Sorry...</p>

</html>

                                    Weather
                                       |
+----------------+---------------------+---------------+-------------------+.....
|                |                     |               |                   |
(first-child)  (second-child)      (third-child)      (fourth-child)   (fifth-child)
strong         strong                em                span                a
                                                        |
                                                +-------+--------+
                                                |                |
                                            first-child     second-child
                                                a                em

我知道,这不是最漂亮的 ascii 示例,但这就是我的想法。

于 2009-07-11T18:36:30.200 回答
3

我想你的意思是

div.weather > strong {color:red;}

这将只选择孩子(第一级嵌套)而不是所有后代。

于 2009-07-11T18:51:38.907 回答
1

first-child表示“作为第一个子元素的元素”,而不是“该元素的第一个子元素”。

所以你的例子意味着“strong那是”的第一个孩子div.weather

如果你想让<strong>div 中所有 s 中的第一个单词变成红色,你需要添加一些标记并执行以下操作:

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">
<html> <head>
<title>How to Write a Good Report</title>
<style type="text/css">
div.weather strong span:first-child {color:red;}
</style>
</head>

<body>

<div class="weather">
It's <strong><span>very</span> <span>very</span></strong> hot
and <strong><span>really</span> <span>incredibly</span></strong> humid.
</div>

</body> </html>
于 2009-07-11T18:36:54.333 回答
0

div.weather strong:first-child 表示选择第一个作为天气子元素的强元素,而不是天气的所有子元素。它只会匹配一个元素。

div.weather strong 匹配作为天气后代的所有强元素。div.weather > strong 匹配所有作为天气直接子元素的强元素。div.weather * strong 匹配weahter 的孙子或后来的所有强元素。

于 2009-07-11T18:35:21.030 回答
0

我认为您对“第一个孩子”的理解是错误的。第一个孩子只是第一个元素。请参阅W3Schools 中的示例

于 2009-07-11T18:37:08.437 回答
0

这两个strong元素都是 的子元素,div但只有第一个元素是第一strong个子元素。所以你只是误解了选择器。

于 2009-07-11T18:38:20.587 回答