我试图设置段落的颜色而不使用div的选择来基本上设置段落的样式。任何人都可以用段落颜色帮助解决我的问题吗?
基本上,我想在CSS中使用组合或子扇区,如果可能的话,多行段落是属于标题的颜色,例如在h3标题下只显示蓝色段落,而h4标题只显示红色段落。
h3 {
color: lime;
}
h3 ~ p {
color: blue;
}
h4 {
color: Orange;
}
h4 ~ p {
color: red;
}
<h3>Heading 1</h3>
<p>This section of the paragraphs only to be shown as blue...</p>
<p>This section of the paragraphs only to be shown as blue...</p>
<h4>Heading 2</h4>
<p>This section of the paragraphs only to be shown as red...</p>
<p>This section of the paragraphs only to be shown as red...</p>
<h3>Heading 1 (Again)</h3>
<p>This section of the paragraphs only to be shown as blue...</p>
<p>This section of the paragraphs only to be shown as blue...</p>
答案 0 :(得分:1)
您可以使用+
选择器代替~
,这样您就可以只定位所需的p
并避免特定/订单问题:
h3 + p,
h3 + p + p{
color: blue;
}
h4 + p,
h4 + p + p{
color: red;
}
&#13;
<h3>Heading 1</h3>
<p>This section of the paragraphs only to be shown as blue...</p>
<p>This section of the paragraphs only to be shown as blue...</p>
<h4>Heading 2</h4>
<p>This section of the paragraphs only to be shown as red...</p>
<p>This section of the paragraphs only to be shown as red...</p>
<h3>Heading 1 (Again)</h3>
<p>This section of the paragraphs only to be shown as blue...</p>
<p>This section of the paragraphs only to be shown as blue...</p>
&#13;
如果~
的数量未定义(CSS的顺序在这里很重要),您可以使用p
来考虑更复杂的选择器
h3 ~ p{ /*target the first ones*/
color: blue;
}
h4 ~ p{ /*target the next ones*/
color: Orange;
}
h4 ~ h3 ~ p { /*target the last ones*/
color: red;
}
&#13;
<h3>Heading 1</h3>
<p>This section of the paragraphs only to be shown as blue...</p>
<p>This section of the paragraphs only to be shown as blue...</p>
<h4>Heading 2</h4>
<p>This section of the paragraphs only to be shown as orange...</p>
<p>This section of the paragraphs only to be shown as orange...</p>
<p>This section of the paragraphs only to be shown as orange...</p>
<p>This section of the paragraphs only to be shown as orange...</p>
<h3>Heading 1 (Again)</h3>
<p>This section of the paragraphs only to be shown as red...</p>
<p>This section of the paragraphs only to be shown as red...</p>
<p>This section of the paragraphs only to be shown as red...</p>
&#13;
答案 1 :(得分:-2)
我发现了一个非常优雅和简单的解决方案,将来对我有所帮助。它使用jQuery,您可能可以在本机JavaScript中使用它,但jQuery函数使它非常简单。
$("h3").nextUntil("h4").css({
"color": "blue"
});
$("h4").nextUntil("h3").css({
"color": "red"
});
&#13;
h3 {
color: lime;
}
h4 {
color: orange;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>This section of the paragraphs only to be shown as blue...</p>
<p>This section of the paragraphs only to be shown as blue...</p>
<h4>Heading 2</h4>
<p>This section of the paragraphs only to be shown as red...</p>
<p>This section of the paragraphs only to be shown as red...</p>
<h3>Heading 1 (Again)</h3>
<p>This section of the paragraphs only to be shown as blue...</p>
<p>This section of the paragraphs only to be shown as blue...</p>
&#13;