CSS combinators let you select elements based on their relationship in the HTML tree. Instead of styling elements one by one, you describe how elements are nested or placed next to each other, which makes your styles more powerful and efficient.
A B): selects any element B inside A, at any depth.A > B): selects only B elements that are direct children of A.A + B): selects the very next B that comes right after A.A ~ B): selects all B siblings that come after A on the same level.These are the four main combinators you will use in CSS selectors:
/* Basic CSS combinator syntax overview */
div p {
color: blue;
}
ul > li {
font-weight: bold;
}
h3 + p {
color: red;
}
h3 ~ p {
font-style: italic;
}
div p → any <p> nested inside a <div>.ul > li → only <li> that are direct children of a <ul>.h3 + p → only the first <p> immediately after an <h3>.h3 ~ p → all <p> siblings after an <h3> at the same level.The descendant combinator uses a single space: A B. It selects B elements that are anywhere inside A, no matter how deeply nested.
/* All <p> elements inside any <div> become blue */
div p {
color: blue;
}
Paragraph inside div (styled)
Paragraph outside div (not styled)
Because the selector is div p, only paragraphs inside a <div> are affected.
The child combinator uses > and selects only direct children of an element.
/* Only direct <li> children of <ul> are styled */
ul > li {
background-color: #28a745;
color: white;
padding: 4px;
}
The nested <li> inside the second list item is a grandchild of <ul>, so it is not matched by ul > li.
The adjacent sibling combinator (A + B) selects the first sibling B that comes immediately after A.
/* Style only the first <p> right after an <h3> */
h3 + p {
font-weight: bold;
color: #dc3545;
}
Paragraph right after heading (styled)
Another paragraph (not styled)
Only the very next <p> after <h3> matches h3 + p. Any later paragraphs are ignored.
The general sibling combinator (A ~ B) selects all siblings B that come after A at the same nesting level.
/* Style all <p> siblings that come after an <h3> */
h3 ~ p {
color: #6f42c1;
font-style: italic;
}
First paragraph (styled)
Second paragraph (styled)
Paragraph before heading (would not be matched)
Every <p> that is a later sibling of <h3> is selected by h3 ~ p. Anything that appears before the heading is not affected.
.card > h2) instead of relying only on element names.<div class="container"> with several <p> tags inside and outside it. Use .container p to style only the paragraphs inside.<ul> with another <ul> inside one item). Use ul > li to style only the top-level items.<h2> heading. First, use h2 + p and observe which paragraph gets styled. Then switch to h2 ~ p and note the difference..card > h3 + p and see how it targets only the first paragraph after a heading inside a card.