如何使用CSS仅选择前三个元素

16

如何使用 :nth-child() 选择器仅选择前三个 元素

section > figure:nth-child( ? ) {
  /* ... */
}
<section>
  <figure>1</figure> <!-- select this -->
  <figure>2</figure> <!-- and this -->
  <figure>3</figure> <!-- and this -->
  <figure>4</figure>
  <figure>5</figure>
  <figure>6</figure>
</section>


3
https://css-tricks.com/useful-nth-child-recipies/ - Pete
1个回答

58

你可以像这样做:

section > figure:nth-child(-n+3) {background: Aqua}
<section>
  <figure>1</figure>
  <figure>2</figure>
  <figure>3</figure>
  <figure>4</figure>
  <figure>5</figure>
  <figure>6</figure>
</section>


1
我喜欢这个解决方案。对于我们中的好奇心旺盛的人来说,我看了一下它是如何工作的 - 这是一个简单的公式,返回3、2和1: -0+3 = 3, -1+3 = 2, -2+3 = 1。 - LaZza

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接