求助:SASS中caution__item类的:first-child选择器为何失效
: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:
Use
:first-of-typeinstead
If all your.caution__itemelements are the same type (e.g., all<div>s), swap:first-childwith: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__itemeven if there are other elements in the parent.Clean up the parent container
Double-check your HTML structure for the.cautioncontainer. 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

