CSS Combinators Flashcards
(11 cards)
Descendant Combinator (space)
Selects elements that are inside another element, at any level.
parent descendant { style }
div p { color: red; } <div> <p>This is inside a div.</p> <section> <p>This is also inside a div.</p> </section> </div> <p>This is outside.</p>
Both <p>
elements inside <div>
turn red, but not the one outside.
Child Combinator (> )
Selects direct children only (not deeper levels).
parent > child { style }
div > p { color: blue; } <div> <p>Direct child</p> <section> <p>Not a direct child</p> </section> </div>
Only the first <p>
turns blue, not the nested one.
Adjacent Sibling Combinator (+ )
Selects an element that comes immediately after another element (same parent).
element1 + element2 { style }
h1 + p { color: green; } <h1>Heading</h1> <p>This is styled.</p> <p>This is NOT styled.</p>
Only the first <p>
after <h1>
turns green.
General Sibling Combinator (~ )
Selects all siblings that come after another element (same parent, but not necessarily next).
element1 ~ element2 { style }
h1 ~ p { color: purple; } <h1>Heading</h1> <p>Styled</p> <p>Also styled</p>
All <p>
elements after <h1>
turn purple.
Combining Combinators
div > p + span { color: orange; } <div> <p>Paragraph</p> <span>This span is styled.</span> <span>This is NOT styled.</span> </div>
Only the first <span>
after <p>
inside <div>
is orange.
<div class="wrapper"> <h2>Main Title</h2> <p>First paragraph</p> <div class="content"> <p>Nested paragraph</p> </div> <p>Another paragraph</p> </div>
You want to apply a style only to the <p>
elements that are direct children of .wrapper
, but not to the nested one inside .content
.
.wrapper > p
.wrapper > p
uses the child combinator, selecting only <p>
elements that are immediate children of .wrapper
.
<div class="article"> <h2>Heading</h2> <p>Paragraph one</p> <div> <p>Nested paragraph</p> </div> </div>
Write a CSS rule to style all <p>
elements inside .article
, including nested ones.
.article p { font-size: 18px; }
<div class="article"> <h2>Heading</h2> <p>Paragraph one</p> <div> <p>Nested paragraph</p> </div> </div>
Write a CSS rule that targets only the top-level <p>
(not the nested one)
.article > p { color: teal; }
<div class="profile"> <h3>Username</h3> <span>Status: Online</span> </div>
Style only the <span>
that immediately follows an <h3>
inside .profile
.
.profile h3 + span { font-weight: bold; }
<div class="faq"> <h4>Question</h4> <p>Answer 1</p> <p>Answer 2</p> </div>
Write a rule that selects all <p>
elements that are siblings of an <h4>
(not necessarily adjacent) inside .faq
.
.faq h4 ~ p { background-color: #f0f0f0; }
<div class="comments"> <div class="comment"> <h5>Author</h5> <p>Comment text</p> <span class="timestamp">1h ago</span> </div> </div>
Write a rule to target only the .timestamp
that is an adjacent sibling of a <p>
, which itself is a direct child of .comment
.
.comment > p + .timestamp { color: gray; font-size: 0.8rem; }