CSS中下一个元素的选择器的语法是什么?

ton*_*ega 192 html css css-selectors siblings

如果我有标头标签 <h1 class="hc-reform">title</h1>

h1.hc-reform{
    float:left;
    font-size:30px;
    color:#0e73bb;
    font-weight:bold;
    margin:10px 0px;
}
Run Code Online (Sandbox Code Playgroud)

然后我有一个段落<p>stuff here</p>.

如何确保使用CSS后面的每个<p>标记h1.hc-reform使用:clear:both;

那会是:

h1.hc-reform > p{
     clear:both;
}
Run Code Online (Sandbox Code Playgroud)

由于某种原因,这是行不通的.

Jos*_*ola 385

这被称为相邻的兄弟选择器,它由加号表示......

h1.hc-reform + p {
  clear:both;
}
Run Code Online (Sandbox Code Playgroud)

注意:IE6或更早版本不支持此功能.

  • 那只会选择`h1.hc-reform`之后的'p`.然后它可能是唯一一个需要应用`clear:both`来使它工作,因为它只是清除`h1`浮点数,所以它仍然是一个有效的答案. (4认同)
  • 哇不知道相邻的兄弟选择器.很好,谢谢! (4认同)

Ste*_*ler 58

您可以使用兄弟选择器 ~:

h1.hc-reform ~ p{
     clear:both;
}
Run Code Online (Sandbox Code Playgroud)

这将选择之后的所有p元素.hc-reform,而不仅仅是第一个元素.


Moi*_*man 13

不是>儿童选择器.

你想要的是 +

所以试试吧 h1.hc-reform + p

浏览器支持不是很好

  • 2020 年:十年后,浏览器支持非常好。只是为 CSS 新手提供的信息。 (3认同)

Ric*_*uen 8

>是一个子选择器.因此,如果您的HTML看起来像这样:

<h1 class="hc-reform">
    title
    <p>stuff here</p>
</h1>
Run Code Online (Sandbox Code Playgroud)

......那是你的票.

但是,如果您的HTML看起来像这样:

<h1 class="hc-reform">
    title
</h1>
<p>stuff here</p>
Run Code Online (Sandbox Code Playgroud)

然后你想要相邻的选择器:

h1.hc-reform + p{
     clear:both;
}
Run Code Online (Sandbox Code Playgroud)

  • 我当然希望他没有在p1里面嵌入p ..而且,相邻只选择第一个p. (4认同)