【问题标题】:Use css variable in nth-child(3n + 3) instead of 3 [duplicate]在 nth-child(3n + 3) 中使用 css 变量而不是 3 [重复]
【发布时间】:2021-02-19 05:17:51
【问题描述】:

我正在尝试在 nth-child() 选择器中使用 CSS 变量,我使用 li:nth-child(3n+3) 为每三个 <li> 赋予某种样式。

这个话题在谷歌上很难找到,我找不到任何适合我的用例的结果。

目前我的代码大致如下:

li {
  width: 25%;
  margin-right: 12.5%;
}
li:nth-child(3n+3) {
  margin-right: 0;
}

我想重构我的代码以便可以轻松更改它,但我不知道如何在 :nth-child(3n+3) 选择器中使用 CSS 变量。我想实现这样的目标:

:root {
  --number: 3;
}
li {
  width: calc(100% / (var(--number) + 1));
  margin-right: calc((100% / (var(--number) + 1)) / (var(--number) - 1));
}
li:nth-child(var(--number)n + var(--number)) {
  margin-right: 0;
}

遗憾的是,:nth-child(✖n + ✖) 在使用 vars 而不是数字时无法按预期工作。我的目标是使用 --number 变量调整整个样式。

我创建了一个 codepen 示例: https://codepen.io/hergi/pen/xxRrmGv

非常感谢任何可以帮助我解决此问题的想法/关键字或资源,在此先感谢

【问题讨论】:

  • 你不能,为此使用 SASS

标签: css css-selectors css-variables


【解决方案1】:

我想你想要这样的东西..
您只需要使用 nth-of-type(3n+3)

您不能在selectors 中使用级联variables。有关更多详细信息,请访问此
Is it possible to use CSS vars in CSS3 selectors?

ul {
  display: flex;
  list-style: none;
}

li {
  width: 25%;
  margin-right: 12.5%;
}

li:nth-of-type(3n+3) {
  margin-right: 0;
}

li:nth-of-type(3n+3) button {
  background: #0095ff;
  color: white;
  border: none;
  border-radius: 3px;
  cursor: pointer;
  padding: 3px;
 }
<ul>
  <li><button>Button</button></li>
  <li><button>Button</button></li>
  <li><button>Button</button></li>
  <li><button>Button</button></li>
  <li><button>Button</button></li>
  <li><button>Button</button></li>
  <li><button>Button</button></li>
  <li><button>Button</button></li>
  <li><button>Button</button></li>
</ul>

【讨论】:

  • 感谢您的回答,但这不是我想要实现的目标,我的目标是能够在我的第 n 个选择器中使用变量而不是固定数字。我能够通过 JS 找到解决方案,因为这些 css nth-selectors 似乎不支持变量
猜你喜欢
  • 2012-04-16
  • 2015-08-12
  • 1970-01-01
  • 2014-03-07
  • 2018-01-12
  • 2021-01-24
  • 1970-01-01
  • 2014-03-21
相关资源
最近更新 更多