【问题标题】:How to select all children except first and last with CSS selectors如何使用 CSS 选择器选择除第一个和最后一个之外的所有子项
【发布时间】:2012-12-08 12:01:14
【问题描述】:

如何选择表格中除第一个和最后一个之外的所有子项?我已经尝试过了,但它最终选择了所有不是第一个的孩子和所有不是最后一个的孩子,最终都是孩子:

table.programs tr td:not(:first-child), table.programs tr td:not(:last-child) {
}

我想要所有既不是第一个也不是最后一个的孩子。我该怎么做?

【问题讨论】:

标签: css css-selectors


【解决方案1】:

我认为这应该适合你:

table.programs tr td:not(:first-child,:last-child)

【讨论】:

  • 好吧,他很难过 CSS 选择器(jQuery 也使用)。但考虑到他发布的语法,重点是没有实际意义 =)。
  • 请注意,如果您在 CSS 中使用此功能,则某些较旧的浏览器不支持此功能。如果可能的话,我会考虑给你所有的第一个和最后一个元素 firstlast 类。
  • jQuery 使用非标准版本的:not(),所以虽然这是一个有效的 jQuery 选择器,但它不是一个有效的 CSS 选择器(目前),所以它不能在样式表中工作。那时“CSS 选择器”和“jQuery 选择器”(来自@Barmar 的评论)之间的区别变得非常重要。见What's the difference in the :not() selector between jQuery and CSS?
  • 没错。 jQuery 的选择器是 CSS 选择器的超集,尽管其中许多是 CSS4 中的。
【解决方案2】:

jQuery 解决方案很好,但如果您想在纯 CSS 中执行此操作,我建议您将规则应用于整个表格,然后为第一个和最后一个孩子重置它们。即:

table.programs tr td { 
  /* your rules here */
}

table.programs tr:first-child td:first-child, 
table.programs tr:last-child td:last-child {
  /* reset your rules here */
}

jsFiddle demo

【讨论】:

  • 我认为你的答案是最好的,因为它是跨浏览器的,所以 7,8(仍然是实际的),旧版 ie 的 windows 手机支持它。
【解决方案3】:

结合使用两个:not()选择器,从而引用同时匹配它们的元素,即不匹配用作:not()操作数的选择器的元素:

table.programs td:not(:first-child):not(:last-child)

【讨论】:

  • @FrankV,您误解了另一个问题及其答案。该问题涉及链式:not() 选择器,但询问是否有替代方案。
  • td+td:not(:last-child)
【解决方案4】:

它是这样工作的

    table.programs tr td:nth-child(1n+2):not(:last-child)

【讨论】:

    【解决方案5】:

    像这样。

    li:nth-child(n+2):nth-last-child(n+2) { background: red; }
    

    满足您的要求

    table.programs tr td:nth-child(n+2):nth-last-child(n+2) { /* Your Style */ }
    

    【讨论】:

      猜你喜欢
      • 2015-05-01
      • 1970-01-01
      • 2012-04-05
      • 2012-02-22
      • 1970-01-01
      • 1970-01-01
      • 2011-12-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多