我正在为带有嵌套评论的论坛编写 CSS 主题。我希望顶级评论有白色背景,二级评论有灰色背景,第三级白色,第四级灰色,第五级白色等。
此样式表适用于前五个级别:
#comments > .comment { background-color: white }
#comments > .comment > .comment { background-color: grey }
#comments > .comment > .comment > .comment { background-color: white }
#comments > .comment > .comment > .comment > .comment { background-color: grey }
#comments > .comment > .comment > .comment > .comment > .comment { background-color: white }
如何编写才能使其始终有效,无论嵌套深度如何?
最佳答案
我认为你不能,但是你可以减少一点代码量。首先,请确保使用子级 (>
),否则注释中的注释中的注释也会被 #comment .comment
匹配。
其次,您可以定义注释的基本样式,并且仅添加第二个第四级(如果您需要第六级等)的特定覆盖。
这样,您就可以为您实际期望的尽可能多的级别定义“覆盖”。如果注释嵌套得更深,它们的样式仍然是基本样式。
/* Base, applies to all comments */
#comments .comment {
background-color: white;
}
/* Overrides for specific levels of nesting */
#comments > .comment > .comment,
#comments > .comment > .comment > .comment > .comment {
background-color: grey
}
关于nth-nested-child 的 CSS 选择器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28929392/