css 兄弟组合子(~)和< p>[duplicate]的问题

ajsxfq5m  于 2023-05-19  发布在  其他
关注(0)|答案(1)|浏览(102)

此问题已在此处有答案

List of HTML5 elements that can be nested inside P element?(1个答案)
3天前关闭。
为什么,在使用<p>标记的情况下,兄弟组合子被应用于没有公共父元素的元素。
在这里,样式应用于,子块的文本变为红色:

div~div {
color: red;
}
<div>Блок 1</div>       
<p>Paragraph 1
    <div>Child Block 1</div>
</p>

这里没有应用样式,div中的文本也没有变成红色:

div~div {
color: red;
}
<div>Блок 1</div>       
<section>Section 1
    <div>Child Block 1</div>
</section>

<p>是否有一些隐藏的属性,或者<div>块是否有一个不可见的公共父块?

3wabscal

3wabscal1#

这里没什么不对的。这是p元素的行为。

Paragraphs are block-level elements, and notably will automatically close if another block-level element is parsed before the closing p tag

所以如果你在p元素中放置任何其他元素,那么p元素会自动关闭。在你的代码中,由于自动关闭,在浏览器上呈现的html是:-

<div>Блок 1</div>       
<p>Paragraph 1</p>
<div>Child Block 1</div>
<p></p>

因为你在CSS中使用General Sibling Selector,所以在这个p元素的例子中第二个div是第一个div的兄弟。这就是为什么CSS应用于第二个div。
而在**section element case**中,如果您在section元素中放置任何其他元素,则section元素不会自动关闭。因此,在section元素的情况下,浏览器上的html呈现为:

<div>Блок 1</div>       
<section>Paragraph 1
   <div>Child Block 1</div>
</section>

而且,在这种情况下,第二个div不是第一个div的兄弟。这就是为什么CSS不适用于第二个div。

相关问题