【问题标题】:CSS selector exclude first child then fallow nth child patternCSS 选择器排除第一个孩子,然后是第 n 个孩子模式
【发布时间】:2018-10-19 21:12:14
【问题描述】:

不知道为什么这不起作用:

:not(first-child):nth-child(3n+2){
  margin-left: 30px;
  margin-right:30px;
}

它通过模式 3n+2,我想从这个模式中排除第一个孩子,这可能吗?

这行得通,但那是 4 行代码。我想减少这个sn-p的代码:

:nth-child(3n+2){
  margin-right:30px;
}
:nth-child(3n+4){
  margin-left: 30px;
}

【问题讨论】:

  • 寻求代码帮助的问题必须包含重现它所需的最短代码在问题本身中最好在Stack Snippet 中。见How to create a Minimal, Complete, and Verifiable example
  • nth-child(3n+2)已经排除第一个孩子吗?
  • @Paulie_D 在这个计数中它仍然包括第一个孩子nth-child(3n+2),如何排除?我想从第二个孩子开始计算这个'nth-child(3n+2)' tahts 为什么我试着把:not(first-child)
  • 我真的不清楚你想要做什么。这就是为什么我们需要一个问题的演示。
  • @Paulie_D 我不认为它需要一个例子,我放了更多的东西让我知道是否有意义

标签: css sass


【解决方案1】:

您需要在第一个孩子之前使用冒号 (:),所以应该是 -

:not(:first-child):nth-child(3n+2){
  margin-left: 30px;
  margin-right:30px;
}

请参考以下代码sn-p。

span {
  color: white;
  float: left;
  margin: 10px;
  padding: 10px;
  background-color: black;
}

span:not(:first-child):nth-child(3n+1) {
  background-color: red;
}

span:nth-child(3n+2) {
  background-color: blue;
}

span:nth-child(3n+3) {
  background-color: green;
}
<html>

<head>
</head>

<body>
  <span>1</span>
  <span>2</span>
  <span>3</span>
  <span>4</span>
  <span>5</span>
  <span>6</span>
  <span>7</span>
  <span>8</span>
</body>

</html>

【讨论】:

  • 您能否发布代码 sn-p 表明它对您有效,而对我无效
  • @user9013856 我在我的答案中添加了一个代码 sn-p 供您参考。请注意,第 (3n+2) 个孩子或第 (3n+3) 个孩子永远不可能是第一个孩子,因此对这两种情况应用 ":not(:first-child)" 将无效。
【解决方案2】:

在此处查看此解决方案我添加 CSS 排除您可以遵循此模式的第一个元素。 Internet Explorer 8 和更早版本不支持:nth-​​child() 选择器。

p:nth-child(1n+2) {
    background: red;
}
<!DOCTYPE html>
<html>
<head>

</head>
<body>

<p>The first.</p>
<p>The second.</p>
<p>The third.</p>
<p>The fourth .</p>
</body>
</html>

【讨论】:

    猜你喜欢
    • 2023-03-16
    • 1970-01-01
    • 1970-01-01
    • 2017-03-11
    • 2023-03-24
    • 2011-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多