LoginSignup
3
1

More than 5 years have passed since last update.

入れ子になったタグの親要素にだけnth-of-typeを使って反映させる

Last updated at Posted at 2017-05-10

nth-of-typeとは

E:nth-of-type(n)は、疑似クラスの一種で、 n番目のその種類の要素にスタイルを適用する際に使用します。

引用元 : CSS3リファレンス E:nth-of-type(n)

nth-childとの違い

似たような擬似クラスで nth-child というものがあるのですが、
大雑把に説明すると、

以下のようなHTMLがあった際に

<div>
    <p>1つ目のPタグ</p>
    <p>2つ目のPタグ</p>
    <span>1つ目のspanタグ</span>
    <p>3つ目のPタグ</p>
    <p>4つ目のPタグ</p>
</div>
div p:nth-of-type(4){
    background-color : red;
}

だと <p>4つ目のPタグ</p> の背景色が になり、

div p:nth-child(4){
    background-color : red;
}

だと <p>3つ目のPタグ</p> の背景色が になる感じです。

要は、nth-of-typeはdivの子で4つ目のpを赤くする
nth-childはdivの子で4番目の要素がpなら赤くするって感じです。

nth-of-typeの場合divの 子であるpだけ をカウントしているのですが
nth-childの場合divの 子である全ての要素 をカウントしています。

スクリーンショット 2017-12-20 9.34.29.png

※今回はこの程度の説明で良いだろうってことで簡単に書いてます。詳しくは別途調べてください。

今回したいこと

例えば、tableの中にtableが作り(つまり入れ子)になってるものに対し
外側のtableの1番目のtdだけを赤くしたいとします。

そこで以下のようなCSSを書いてしまうと

table.table1 td:nth-of-type(1){
    background-color : red;
}

以下のように入れ子になっているテーブルにまで影響が出てしまいます。

<table class='table1'>
    <tbody>
        <tr>
            <td>
            ここの背景を赤くしたい
            </td>

            <td>
                <table>
                    <tbody>
                        <tr>
                            <td>ここまで赤くなる</td>
                        </tr>
                    </tbody>
                </table>
            </td>
        </tr>
    </tbody>
</table>

解決

> セレクタ を使います。
> セレクタを使うと ある要素の直下の階層にある要素にスタイルに適用されるので、
以下のように書きます。

table.table1>tbody>tr>td:nth-of-type(1){
    background-color : red;
}

最後に

tableを入れ子にするくらいならdivで組めば良いと思う。

※何か他に良い方法があれば教えてください

3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1