CSS 3のセレクタ「:nth-child()」の問題を回避する方法と応用例
エ・ビスコム・テック・ラボ
2008-12-24 18:18:00
前回、リストのデザインに適用したCSS 3のセレクタ「:nth-child()」。今回は:nth-child()をコンテンツへ適用する際に発生する問題とその解決法、応用例を紹介する。
応用例
:nth-of-type()や前回紹介した:first-child、:last-childを利用すると、次のようなデザインを設定することもできる。ここでは見出しの文字を交互に色分けし、全体を画像の枠で囲んで表示している。
見出しを色分けして、全体を画像の枠で囲んで表示したもの
h2:nth-of-type(odd){
color: limegreen;
}
h2:nth-of-type(even){
color: navy;
}
div{
background-image: url(border02.png);
background-repeat: repeat-y;
}
div *:first-child{
background-image: url(border01.png);
background-repeat: no-repeat;
padding-top: 20px;
}
div *:last-child{
background-image: url(border03.png);
background-repeat: no-repeat;
background-position: left bottom;
padding-bottom: 20px;
}
まず、見出しの文字の色はh2:nth-of-type(odd)とh2:nth-of-type(even)で指定している。
次に、画像の枠は以下の3つの画像を利用して表示する。このうち、border01.pngは:first-child()を利用して<div>内の最初の要素に、border03.pngは:last-child()を利用して<div>内の最後の要素に背景画像として表示して、枠の上下を構成する。また、枠の中間を構成するborder02.pngは、<div>の背景画像として表示する。
次回は、nth-of-type()を応用して、スタイルシートの設定を3要素おきに適用したり、最初の3要素にだけ適用する方法を紹介したい。
- ホワイトペーパー



