nth-nested-child 的 CSS 选择器

标签 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 }

如何编写才能使其始终有效,无论嵌套深度如何?

最佳答案

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

相关文章:

javascript - 在没有指定高度的静态定位 div 之后定位元素

html - 如何使背景图像滚动而不平铺在页面上?

html - 我可以使用纯 CSS 根据 URL 的获取参数设置链接样式吗?

css - 媒体查询如何计入 IE 的 CSS 选择器限制?

html - 优先选择器不适用于 div 元素

css - iPhone/mobile safari = .css 文件阻止并发服务器请求?

javascript - 每行两个div的AngularJS ng-repeat网格

jquery - Bootstrap 3 的分割按钮插入符高度小于主按钮

CSS >(选择器)不工作

html - 一线伪元素不适用于 p 元素