LoginSignup
97
80

More than 5 years have passed since last update.

要素の個数に応じてスタイルを出し分けるCSSメモ

Last updated at Posted at 2016-06-22

JSを使わずにCSSだけで、
「要素の個数に応じてスタイルを出し分ける」やり方の紹介です。
前にどこかのサイトで紹介されてたのですがブックマークなかったのでメモです。

Demo

"個数に応じたスタイルの出し分け"
http://codepen.io/skwbr/pen/JKbNMP

cap_ 2016-06-22 15.15.35.png

説明

個数に応じてスタイルを変える場合、下記を組み合わせて使います。

  • :nth-last-child 擬似クラス … 最後から数えて何番目か
  • 間接セレクタ ~ … それ以降の後続する弟要素(同階層)
<ul>
  <li class="item"></li>
  <li class="item"></li>
  <li class="item"></li>
    :
</ul>

という作りと想定したとき、


.item:first-child:nth-last-child(5),
.item:first-child:nth-last-child(5) ~ .item {
}

と書くと、.item の合計5つの時のスタイルを定義できます。
最初の1つめが、最後から数えて5つめになるためです。
~ を使って、後続する2番目〜5番目の要素にも同じスタイルを適応します。

コード

css

/* 1つの場合 */
.item:only-child {
}

/* 2つの場合 */
li:first-child:nth-last-child(2),
li:first-child:nth-last-child(2) ~ li {
}

/* 3つの場合 */
.item:first-child:nth-last-child(3),
.item:first-child:nth-last-child(3) ~ .item {
}

/* 4つの場合 */
.item:first-child:nth-last-child(4),
.item:first-child:nth-last-child(4) ~ .item {
}

/* 5つの場合 */
.item:first-child:nth-last-child(5),
.item:first-child:nth-last-child(5) ~ .item {
}

/*   以下略    */

Sass の for文で書く

定義スタイルが個数と相関があって機械的に書けるなら、SCSSの for 文でスマートにかけると思います。例えば…

scss

.item {
  &:first-child {

    @for $i from 1 through 12 {
      &:nth-last-child(#{$i}) {
        &,
        & ~ .item {
          width: percentage(1/$i);
        }
      }
    }

  }
}

と書けば、個数に応じて横幅を均等割りする記述を1個〜12個版まで書けますね。
また、-child ではなく -of-type でも良いと思います。

レガシーブラウザで使いたい場合は、
IE8以前で :nth-last-child が使えないので注意です。
http://caniuse.com/#search=~

97
80
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
97
80