You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用CSS的:nth-child()选择器选中前三个元素?

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

嘿,要实现只选中<section>下的前三个<figure>元素,你可以用:nth-child(-n+3)这个选择器写法,我给你拆解下逻辑:

  • n在这里代表从0开始的整数(0、1、2、3...)
  • 当计算-n+3时:
    • 当n=0 → 3 → 匹配第3个元素
    • 当n=1 → 2 → 匹配第2个元素
    • 当n=2 → 1 → 匹配第1个元素
    • 当n≥3 → 结果≤0 → 不再匹配任何元素

这样就精准选中了前三个子元素啦。下面是完整的代码示例:

CSS 代码

section > figure:nth-child(-n+3) {
  /* 这里写你的样式,比如给选中的元素加个背景色 */
  background-color: #f0f0f0;
}

HTML 代码

<section>
  <figure>1</figure> <!-- 选中这个 -->
  <figure>2</figure> <!-- 还有这个 -->
  <figure>3</figure> <!-- 以及这个 -->
  <figure>4</figure>
  <figure>5</figure>
  <figure>6</figure>
</section>

另外补充个小知识点:如果你的<section>里还有其他类型的元素(不只是<figure>),那:nth-child会把所有子元素都算进去,这时候你可能需要用:nth-of-type(-n+3)来只针对<figure>类型的元素选择前三个哦。

内容的提问来源于stack exchange,提问作者Bariq Dharmawan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 06:21:52