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

疑似セレクターは、あなたが思っていることをしないからです。

.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

これは最もきれいなアスキーの例ではありませんが、私はそれをどのように考えていますか。

于 2009-07-11T18:36:30.200 に答える
3

私はあなたが意味したと思います

div.weather > strong {color:red;}

これにより、すべての子孫ではなく、子のみ(ネストの第1レベル)が選択されます。

于 2009-07-11T18:51:38.907 に答える
1

first-child「この要素の最初の子」ではなく、「最初の子である要素」を意味します。

したがって、あなたの例は「strongの最初の子であるdiv.weather」ことを意味します。

たとえば、div 内のすべての<strong>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

両方strongの要素は の子ですが、最初の要素divだけが最初のstrong子です。つまり、セレクターを誤解しているだけです。

于 2009-07-11T18:38:20.587 に答える
0

div.weather strong:first-child は、weather のすべての子要素ではなく、weather の子である最初の強い要素を選択するように指示します。単一の要素にのみ一致します。

div.weather strong は、weather の子孫であるすべての strong 要素に一致します。div.weather > strong は、weather の直接の子であるすべての strong 要素に一致します。div.weather * strong は、weahter の孫以降のすべての strong 要素に一致します。

于 2009-07-11T18:35:21.030 に答える
0

「第一子」の理解が間違っていると思います。最初の子は最初の要素のみです。W3Schoolsの例を参照してください。

于 2009-07-11T18:37:08.437 に答える