在纯css中是否有一种优雅的方式来匹配仅第一个后代 - 类似于jquery first()?
在jQuery中:
$(".outer .title").first();
标记会有所不同,因此使用直接后代>选择器不可靠。
<div class="outer">
<div class="title"></div>
<div class="inner">
<div class="title" />
</div>
</div>
谢谢!
答案 0 :(得分:2)
答案 1 :(得分:1)
更新:此答案基于现在已在问题中编辑的结构:
<div class="outer">
<div class="thing">
<div class="inner">
<div class="thing" />
</div>
</div>
</div>
使用这样的嵌套,如果对象在其自身内,最好的选择是恢复样式;
.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 */ }
但这两种结构都很愚蠢。这看起来像标题/小标题,在这种情况下你可以这样做:
<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>