nth-nested-child的CSS选择器

时间:2015-03-08 17:12:46

标签: css css-selectors

我正在为具有嵌套评论的论坛编写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 }

如何编写它以便无论嵌套深度如何都能一直工作?

1 个答案:

答案 0 :(得分:1)

我认为你不能,但你可以减少一点代码量。首先,确保使用孩子(>),否则评论中的评论中的评论也会被#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 
}