且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

只匹配纯css中的第一个后代?

更新时间:2023-02-19 11:12:55

更新:此回答基于现在已在问题中编辑的结构:

Update: this answer is based on a structure which has now been edited in the question:

<div class="outer">
    <div class="thing">
        <div class="inner">
            <div class="thing" />
        </div>
    </div>
</div>

对于这样的嵌套,***的选择是恢复对象在自身内部;

With nesting like that, the best option is to revert the styles if the object is within itself;

.outer .thing { /* styles */ }
.thing .thing { /* revert styles */ }

使用这样的结构:

<div class="outer">
    <div class="thing" />
    <div class="inner">
        <div class="thing" />
    </div>
</div>

您有较少的选项;

/* assume thing will always be a direct child of outer */
.outer > .thing {}

/* assume thing will always be the VERY FIRST child of outer */
.outer > thing:first-child {}

/* assume thing will always be inside the VERY FIRST child of outer */
.outer > .thing:first-child, .outer > *:first-child .thing {}

/* assume the thing you don't want will always be inside inner */
.outer .thing {}
.inner .thing { /* revert styles */ }

这看起来像标题/子标题,在这种情况下你可以这样做:

Both structures are silly though. This looks like headings/sub-headings, in which case you can do this:

<header>
    <h1></h1>
    <p></p>
</header>

<hgroup>
    <h1></h1>
    <h2></h2>
</hgroup>

或远离标准标签:

<div class="outer">
    <div class="title" />
    <div class="subtitle" />
</div>

或使用多个类别

<div class="outer">
    <div class="title maintitle" />
    <div class="inner">
        <div class="title subtitle" />
    </div>
</div>