【问题标题】:nth-child and before第 n 个孩子及之前
【发布时间】:2012-04-08 11:12:06
【问题描述】:

我遇到了 CSS 问题,我需要解决这个问题

article div#comments-wrapper ul.sub-comment:before {
    width:1px;
    height:67px;
    background-color:#e4e4e4;
    position:absolute;
    margin-left:-595px;
    margin-top:-36px;
    content:'';
}
article div#comments-wrapper ul.sub-comment:nth-child(1):before {
    height:37px;
    margin-top:-6px;
}

但是我不能放两个这样的伪元素,而且我已经测试过了(不起作用), 也尝试了一些其他的方法,但没有设法弄清楚。

【问题讨论】:

  • 我很确定这行得通。你到底面临什么问题?
  • 这是有效的,但当前的实现可能无法正确解释它。
  • 以下作品:jsfiddle.net/9KkeK。所以你的问题出在其他地方。
  • jsfiddle.net/9KkeK/1 我在那里发布了我的代码,一行应该是红色的,另一行应该是蓝色的..:S
  • 啊,:nth-child() 与类一起使用的经典问题。你会有任意数量的 .sub-comment 项目(即不仅仅是 2 个)吗?

标签: css css-selectors pseudo-element


【解决方案1】:

:nth-child() 不按类或任何东西过滤。在您的代码中,您的第一个 ul.sub-comment 不是 #comments-wrapper 中的第一个孩子,因此它不起作用。

改为使用 this selector technique 并反转您的 heightmargin-top 样式,如下所示:

article div#comments-wrapper ul.sub-comment:before {
    width:1px;
    height:37px; /* was 67px in your code */
    background-color:#e4e4e4;
    position:absolute;
    margin-left:-595px;
    margin-top:-6px; /* was -36px in your code */
    content:'';
}
article div#comments-wrapper ul.sub-comment ~ ul.sub-comment:before {
    height:67px; /* was 37px in your code */
    margin-top:-36px; /* was -6px in your code */
}

基本上,代替:nth-child(1)(或:first-child),使用兄弟选择器和另一个ul.sub-comment将原始样式应用于所有后续ul.sub-comment元素在第一个之后 em>。

Updated fiddle(也反转了background-color 样式,所以第一个保持蓝色)

【讨论】:

    猜你喜欢
    • 2017-03-11
    • 1970-01-01
    • 2012-06-13
    • 2011-01-11
    • 2016-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多