first-child疑似クラス・セレクタ(cfirst-child pseudo-clas)は、要素E が親要素の最初の要素の場合、セレクタ以降で定義されるスタイルを適用します。
E:first-child
次の例はpが親要素の最初の要素である場合にスタイルを適用します。
body {black;} p:first-child {color:red;}
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 5 Transitional//EN"> <html lang="ja-JP"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>CSSのセレクタの使用例</title> <meta name="description" content="CSSのセレクタの使用例です" /> <meta http-equiv="Content-Style-type" content="text/css"> <link rel="stylesheet" href="first_child_selector_sample.css" type="text/css"> </head> <body> <!-- <span>body/span</span> --> <p>body/p1 <span> body/p/span </span> </p> <p>body/p2</p> <span> <p>body/div/p1</p> <p>body/div/p2</p> </span> </body> </html>
チャイルド・セレクタ組み合わせることで親要素を限定することもできます。
E > F:first-child
次の例はspan要素の最初の要素がp要素の時に、そのp要素にスタイルを適用します。
body {black;} span > p:first-child {color:red;}
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 5 Transitional//EN"> <html lang="ja-JP"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>CSSのセレクタの使用例</title> <meta name="description" content="CSSのセレクタの使用例です" /> <meta http-equiv="Content-Style-type" content="text/css"> <link rel="stylesheet" href="first_child_selector_sample2.css" type="text/css"> </head> <body> <p> body/p1 </p> <p> body/p2 </p> <span> <p> body/span/p1 </p> <p>body/span/p2</p> </span> </body> </html>