今回は、pタグ・li・dt・ddなど、連続して使うタグの何番目かにだけ特別なCSSをあてる方法を備忘録します。
■以下のようなHTMLをベースとして考えます。
■htmlの記述
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<div id="test"> | |
<p>1番目のpタグです。</p> | |
<p>2番目のpタグです。</p> | |
<p>3番目のpタグです。</p> | |
<p>4番目のpタグです。</p> | |
<p>5番目のpタグです。</p> | |
<p>6番目のpタグです。</p> | |
<p>7番目のpタグです。</p> | |
<p>8番目のpタグです。</p> | |
<p>9番目のpタグです。</p> | |
</div> |
■cssの記述
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#test p{ | |
width:300px; | |
border:1px #333 solid; | |
padding:5px; | |
} |

■初めの要素のみにCSSを適用する記述。
■cssの記述
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#test p:first-child{ | |
width:300px; | |
border:1px #333 solid; | |
padding:5px; | |
} |

■最後の要素のみにCSSを適用する記述。
■cssの記述
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#test p:last-child{ | |
width:300px; | |
border:1px #333 solid; | |
padding:5px; | |
} |

■上から5番目の要素にCSSを適用する記述。
■cssの記述
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#test p:nth-child(5){ | |
width:300px; | |
border:1px #333 solid; | |
padding:5px; | |
} |

★完成★
n番目の指定は、そのタグ数の順番に依存するため、使い所に注意しましょう。