2013/01/17

CSS3で要素に繰り返しスタイルを適用する方法

このエントリーをはてなブックマークに追加

リストやテーブルの行に繰り返してスタイルを指定する方法があります。 Ardor(@ArdorOnline)です。 以前は、奇数に"odd"、偶数に"even"とクラスを指定して対応することが多かったです。 CSS3からは、構造擬似クラスを使って、もっと簡単に指定が行えます。簡単にご紹介します。

構造擬似クラス

構造擬似クラスはいくつかあるのですが、 リストやテーブル要素などに繰り返しスタイルを指定するときには、 ":nth-child"が便利です。主な使い方は次の通りです。

セレクタ 適用先 サンプル
:nth-child 奇数要素に適用 li:nth-child(odd) {
  background-color: white;
}
偶数要素に適用 li:nth-child(even) {
  background-color: white;
}
奇数要素に適用(an+b) li:nth-child(2n+1) {
  background-color: white;
}
偶数要素に適用(an+b) li:nth-child(2n+2) {
  background-color: white;
}
3つおきに適用(an+b) li:nth-child(3n+1) {
  background-color: white;
}
li:nth-child(3n+2) {
  background-color: white;
}
li:nth-child(3n+3) {
  background-color: white;
}
最初の3つに適用(an+b) li:nth-child(-n+3) {
  background-color: white;
}

スタイルシートの記述

リストに対して適用する記述例です。

.sample1 li:nth-child(odd) {
 background-color: greenyellow;
}
.sample1 li:nth-child(even) {
 background-color: yellow;
}
.sample2 li:nth-child(2n+1) {
 background-color: greenyellow;
}
.sample2 li:nth-child(2n+2) {
 background-color: yellow;
}
.sample3 li:nth-child(3n+1) {
 background-color: greenyellow;
}
.sample3 li:nth-child(3n+2) {
 background-color: yellow;
}
.sample3 li:nth-child(3n+3) {
 background-color: lightskyblue;
}
.sample4 li:nth-child(-n+3) {
 background-color: lightskyblue;
}

サンプル

nth-child(odd)、nth-child(even)で指定した場合のサンプル

  • 奇数行
  • 偶数行
  • 奇数行
  • 偶数行

nth-child(2n+1)、nth-child(2n+2)で指定した場合のサンプル

  • 奇数行
  • 偶数行
  • 奇数行
  • 偶数行

nth-child(3n+1)、nth-child(3n+2)、nth-child(3n+3)で指定した場合のサンプル

  • 1行目
  • 2行目
  • 3行目
  • 4行目
  • 5行目
  • 6行目
  • 7行目

nth-child(-n+3)で指定した場合のサンプル

  • 1行目
  • 2行目
  • 3行目
  • 4行目
  • 5行目
  • 6行目
  • 7行目

最後に

リストのみご紹介しましたが、テーブルでも同じことが可能です。
nth-childには、もう少し応用した使い方があります。
またの機会にご紹介してみます。

最後までお読み頂きありがとうございます。

0 件のコメント:

コメントを投稿

ブログ アーカイブ