我如何使用 first of type 或 first child 来仅定位顶级类型。不是嵌套的?

How can I use first of type or fist child to target only the top level one. Not the nested one?

你好我想要目标 class = 'section', 我怎样才能使用 first of type 或 fist child 只针对顶级。不是嵌套的?

    .site-content > .section-wrap > .section {
        margin-top: 1.5vmax;
    }


<div class="site-content">
    <div class="section-wrap">
        <div class="section">Target This</div>
        <div class="section">Target This</div>
        <div class="section">Target This
            <div class="site-content">
                <div class="section-wrap"></div>
                <div class="section">Not this</div>
            </div>
        </div>
        div class="section">Target This</div>
        div class="section">Target This</div>
        </div>
</div>

根据您的标记

.site-content > .elementor-section-wrap + .elementor-section

如果您不想 select 嵌套的,您可以通过 :not selector

:not(.site-content)  .site-content > .elementor-section-wrap + .elementor-section

您将无法使用 :first-of-type 或 :first-child 仅定位顶层而忽略嵌套的。

这两个伪 css 选择器都会检查子项是否为直接父项。

例如,:first-of-type 的作用是:

和 :first-child 的作用是:

如果您发布的 HTML 代码仅由 body 元素包裹,您可以使用此选择器:

body > .site-content > .section-wrap > .section {
    margin-top: 1.5vmax;
}

如果 body 和第一级 .site-content 之间有另一个元素,请将其包含在选择器中,同时使用 > 运算符 direct后代。