問題描述
對(duì)于這個(gè)問題,我使用以下標(biāo)記:
<body><p>1</p><!-- 第1段--><p>2</p><!-- 第2段--><p>3</p><!-- 第 3 段 --></身體>
根據(jù) .
* + *
為從文檔根開始的任何元素的直接兄弟元素設(shè)置樣式 - 由于 <head>
實(shí)際上是正文的緊前同級(jí)(盡管在您的代碼中不可見),此選擇器針對(duì)正文和最后兩段,因?yàn)榈谝欢尾皇蔷o跟在另一個(gè)同級(jí)元素之后.由于正常流程中塊級(jí)后代的 text-decoration
的性質(zhì),所有三個(gè)段落都加了下劃線.
* ~ *
這基本上和上面一樣,除了使用 通用兄弟組合器 .. 它設(shè)置出現(xiàn)在 <head>
之后的下游兄弟元素,無論它們是否是直接兄弟.由于 <body>
是唯一的兄弟,所以它與上面的選擇器具有相同的效果.由于繼承,第一段為斜體.
p ~ *
選擇一個(gè) 跟隨 <p>
的兄弟元素,在您的示例中是最后兩段.p + *
為段落的直接兄弟元素設(shè)置樣式,這也是最后兩個(gè) <p>
元素.
For this question I'm using the following markup:
<body>
<p>1</p> <!-- Paragraph 1 -->
<p>2</p> <!-- Paragraph 2 -->
<p>3</p> <!-- Paragraph 3 -->
</body>
From the Selectors Level 3 specification, the following selector rules apply:
* any element
E + F an F element immediately preceded by an E element
E ~ F an F element preceded by an E element
Based on this, the following should occur:
body + * { } /* Selects nothing as no elements precede body */
body ~ * { } /* As above. */
p + * { } /* Selects Paragraph 2 and Paragraph 3 as these are preceded by p */
p ~ * { } /* As above. */
* + * { } /* As above. */
* ~ * { } /* As above. */
False!
* + *
and * ~ *
are somehow able to select Paragraph 1 along with 2 and 3! Paragraph 1 isn't preceded by anything, so should be impossible to access:
body + * { background: #000; }
body ~ * { background: #000; }
p ~ * { color: #f00; }
p + * { font-weight: bold; }
* + * { text-decoration: underline; }
* ~ * { font-style: italic; }
Result:
As you can see, paragraph 1 isn't preceded by the body
or a phantom p
, yet it is apparently preceded by something. It should have no custom styling applied to it at all, yet is somehow affected by those last two selectors. What is the logic behind this?
JSFiddle example.
* + *
Styles any element that is an immediate sibling of any element starting from the document root - Since the <head>
is actually an immediate preceding sibling of the body (despite not being visible in your code) this selector targets the body and the last two paragraphs, since the first paragraph isn't immediately following another sibling element. All three paragraphs happened to be underlined due to the nature of text-decoration
on block-level descendants in the normal flow.
* ~ *
This is basically the same thing as above, except using the general sibling combinator .. it styles downstream sibling element(s) that appear after the <head>
regardless of whether they're immediate siblings or not. Since the <body>
is the only sibling, this has the same effect as the above selector. The first paragraph is italicized due to inheritance.
p ~ *
selects a sibling element that is following a <p>
which in your example is the last two paragraphs. p + *
styles any element that is immediate sibling of a paragraph, which would also be the last two <p>
elements.
這篇關(guān)于兄弟選擇器 * + * 和 * ~ * 背后的邏輯是什么?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!