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

求助:SASS中caution__item类的:first-child选择器为何失效

Why isn't your SASS :first-child selector working?

Hey there! Let's break down why your :first-child rule isn't targeting the element you expect.

The core issue with :first-child

The :first-child pseudo-class doesn't just target the first element matching your selector—it targets the first child element of the parent container, only if that child matches your selector.

In your compiled CSS, the rule becomes:

@media (max-width: [your-sm-max-value]) {
  .caution__item:first-child {
    padding-top: 50px;
  }
}

This will only apply if the very first child of the .caution container is a .caution__item element. If there's anything else before it—like a text node (even just whitespace), a <span>, <h3>, or any other element—this selector won't trigger.

How to fix it

You have two solid options here:

  1. Use :first-of-type instead
    If all your .caution__item elements are the same type (e.g., all <div>s), swap :first-child with :first-of-type. This selector targets the first element of its type within the parent, regardless of what comes before it. Your SASS would look like:

    &:first-of-type {
      padding-top: 50px;
    }
    

    Compiled, this becomes .caution__item:first-of-type, which will hit the first .caution__item even if there are other elements in the parent.

  2. Clean up the parent container
    Double-check your HTML structure for the .caution container. Make sure the first child inside it is exactly a .caution__item—no stray text, comments, or other elements before it. For example:

    <!-- Good: first child is .caution__item -->
    <div class="caution">
      <div class="caution__item">...</div>
      <div class="caution__item">...</div>
    </div>
    
    <!-- Bad: first child is a heading, so :first-child won't work -->
    <div class="caution">
      <h3>Caution Notes</h3>
      <div class="caution__item">...</div>
    </div>
    

Quick check to confirm

You mentioned your &:last-child rule (the red background) is working—this makes sense if the last child of .caution is a .caution__item, but the first child isn't. That mismatch is a clear sign the parent container has extra content before the first item.

内容的提问来源于stack exchange,提问作者Halit Güvenilir

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 10:12:39