隣接兄弟セレクター
CoddyのHTMLジャーニー「CSS Mastery」セクションの一部 — レッスン 4/43。
隣接兄弟セレクタ (+) は、特定の要素の直後に来る要素にスタイルを適用するために使用されます。両方の要素は同じ親を持っている必要があり、「隣接」とは「互いにすぐ隣にある」ことを意味します。
例えば:
<h2>Heading</h2>
<p>This paragraph is styled</p>次のCSSを使用すると:
h2 + p {
font-weight: bold;
}この段落はh2要素の直後にあるため、スタイルが適用されています。
このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。
このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。
チャレンジ
簡単バスケットボールの試合について説明している <h2> 要素の直後に続く段落(<p>)のみを対象とするCSSセレクタを作成してください。これらの段落に blue のフォント色と 18px のフォントサイズを適用してください。
チートシート
隣接兄弟セレクタ (+) は、特定の要素の直後に来る要素にスタイルを適用します。両方の要素は同じ親を持っている必要があります。
構文:
element1 + element2 {
/* スタイル */
}例:
h2 + p {
font-weight: bold;
}これは、h2要素の直後に続くp要素を対象にします。
自分で試してみよう
<html>
<head>
<title>Adjacent Sibling Selector</title>
<style>
/* CSS solution goes here */
</style>
</head>
<body>
<h2>Basketball Game Overview</h2>
<p>The basketball game was an exciting match between the **Los Angeles Lakers** and the **Golden State Warriors**, featuring intense offense and solid defense from both teams.</p>
<p>During the first half, the Lakers held a slight lead, with LeBron James making key plays, while Stephen Curry of the Warriors kept the game tight with impressive three-pointers.</p>
<p>This paragraph is not directly after an h2, so it should not be affected.</p>
<p>In the second half, the Warriors fought back, with Klay Thompson hitting critical shots, but the Lakers secured their win with solid defense and a game-winning dunk by Anthony Davis.</p>
</body>
</html>
このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。