<!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>
为什么只有“very”是红色而“incredibly”不是红色,因为它们都是“div.weather strong”指定元素的第一个子元素?
最佳答案
因为伪选择器并没有按照您的想法去做。
在您陈述的示例中,它选择元素 .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 示例,我知道,但这是我的想法。
关于CSS伪类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1114353/