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

时间:2013-03-29 22:27:22

标签: jquery css

在纯css中是否有一种优雅的方式来匹配第一个后代 - 类似于jquery first()?

在jQuery中:

$(".outer .title").first();

标记会有所不同,因此使用直接后代>选择器不可靠。

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

谢谢!

2 个答案:

答案 0 :(得分:2)

查找CSS选择器 - W3Schools CSS Selectors

这可能是你正在寻找的东西:
.outer .thing:first-child {}

您也可以尝试nth-child()

答案 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>