0

jquery first() のように、純粋な css で最初の子孫のみに一致するエレガントな方法はありますか?

jQueryで:

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

マークアップはさまざまであるため、直接の子孫 > セレクターの使用は信頼できません。

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

ありがとう!

4

2 に答える 2

2

CSS セレクターを検索する - W3Schools CSS セレクター

これはあなたが探しているものかもしれません:
.outer .thing:first-child {}

あなたも試すことができますnth-child()

于 2013-03-29T22:32:01.993 に答える
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>
于 2013-03-29T22:32:17.720 に答える