我正在使用 PHP 和 MySQL 构建一个网站,其中包含文章,并且每篇文章都可以包含评论(就像典型的博客一样)。每篇文章页面都是这样的
<?php
$blog_id = "1";
include("../includes/blog.php");
?>
所有代码都在 blog.php 中。
目的是每个页面上的评论应该具有交替的背景颜色,以便在一条评论结束和另一条评论开始时清晰可见。我正在使用这个 CSS 来实现它
.comment:nth-child(2n+1){background-color:rgba(0,0,0,0.075)}
因此,据我了解,第一条、第三条等评论应为浅灰色,而第二条、第四条等评论应为白色背景。
The first article I created底部有一条评论,正如预期的那样,它是灰色的。 The second article还有一条评论,但背景是白色的。使用 Chrome 中的代码检查器显示它没有拾取 CSS 的“nth-child”行。当我临时添加第二个虚拟注释时,它具有灰色背景,因此它似乎适用于偶数元素而不是奇数元素。
我在这里阅读了许多类似的问题,但没有一个让我找到解决方案。我尝试过 nth-child(odd)
而不是 nth-child(2n+1)
但没有什么区别。我什至尝试将所有注释包装在另一个 div 中并使用此 CSS,但这确实通过将其自身应用到注释中的嵌套段落而把事情搞砸了。
.comment-wrapper :nth-child(2n+1){background-color:rgba(0,0,0,0.075)}
任何实用的建议将不胜感激。谢谢。
最佳答案
nth-child
伪选择器实际上作用于子级,而不是父级。
此 CSS 选择器查找类为 .comment
且为奇数子元素的元素:
.comment:nth-child(2n+1)
.comment:nth-child(2n+1) {
color: red;
}
<div class="comment">
<p>1</p>
<p>2</p>
<p>3</p>
<p>4</p>
</div>
<div class="comment">
<p>1</p>
<p>2</p>
<p>3</p>
<p>4</p>
</div>
此 CSS 选择器查找具有类 .comment
的元素的奇怪直接子元素:
.comment > :nth-child(2n+1)
.comment > :nth-child(2n+1) {
color: red;
}
<div class="comment">
<p>1</p>
<p>2</p>
<p>3</p>
<p>4</p>
</div>
<div class="comment">
<p>1</p>
<p>2</p>
<p>3</p>
<p>4</p>
</div>
您的新规则将如下所示:
.comment > :nth-child(2n+1) {
background-color: rgba(0,0,0,0.075);
}
使用 >
直接子组合器而不只是
空格(后代组合器)的原因是,我们不会像您提到的那样以注释内的嵌套元素为目标在您的其他尝试之一中也发生过这种情况。
我建议在选择器中使用odd
以提高可读性并使用新的CSS颜色语法:
.comment > :nth-child(odd) {
background-color: rgb(0 0 0 / 0.075);
}
关于css - nth-child 可以在一页上工作,但不能在另一页上工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72492272/