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

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

h1.hc-reform{
float:left;
font-size:30px;
color:#0e73bb;
font-weight:bold;
margin:10px 0px;
}

在这之后,我有一个段落<p>stuff here</p>

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

会是:

h1.hc-reform > p{
clear:both;
}

出于某种原因,这行不通。

311461 次浏览

这被称为相邻的兄弟姐妹选择器,它由一个加号…

h1.hc-reform + p {
clear:both;
}

注意:这在IE6或更老版本中不支持。

no >是子选择器。

你想要的是+

所以试试h1.hc-reform + p

浏览器支持不是很好

>是一个子选择器。如果你的HTML是这样的:

<h1 class="hc-reform">
title
<p>stuff here</p>
</h1>

... 那就是你的票了。

但是如果你的HTML是这样的:

<h1 class="hc-reform">
title
</h1>
<p>stuff here</p>

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

h1.hc-reform + p{
clear:both;
}

你可以使用兄弟姐妹选择器 ~:

h1.hc-reform ~ p{
clear:both;
}

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

不完全是。h1.hc-reform > p表示“恰好在h1.hc-reform下面一层的任何p”。

你想要的是h1.hc-reform + p。当然,这在旧版本的ie浏览器中可能会导致一些问题;如果你想让页面与旧的ie兼容,你会被困在手动添加类到段落或使用一些JavaScript(在jQuery中,例如,你可以做一些像$('h1.hc-reform').next('p').addClass('first-paragraph'))。

更多信息:http://www.w3.org/TR/CSS2/selector.htmlhttp://css-tricks.com/child-and-sibling-selectors/