CSS Combinators (Child, Descendant, Sibling)

Introduction CSS combinators define relationships between elements, allowing precise styling. They include descendant ( ), child (>), adjacent sibling (+), and general sibling (~). 1. Descendant Combinator ( ) Targets elements nested within a specific parent. Example: This styles <p> inside <div> but not direct children only. 2. Child Combinator (> ) Selects direct children […]

  • Post author:
  • Post category: CSS
  • Reading time: 18 mins read
  • Post last modified: April 3, 2025

Introduction

CSS combinators define relationships between elements, allowing precise styling. They include descendant ( ), child (>), adjacent sibling (+), and general sibling (~).

1. Descendant Combinator ( )

Targets elements nested within a specific parent.

Example:

div p {
    color: blue;
}
CSS

This styles <p> inside <div> but not direct children only.

2. Child Combinator (> )

Selects direct children only.

Example:

div > p {
    font-weight: bold;
}
CSS

This affects only <p> elements directly inside <div>.

3. Adjacent Sibling Combinator (+)

Targets an element immediately following another.

Example:

h1 + p {
    font-style: italic;
}
CSS

Styles the first <p> after <h1>.

4. General Sibling Combinator (~)

Applies styles to all matching siblings after a given element.

Example:

h1 ~ p {
    color: red;
}
CSS

Styles all <p> elements after <h1>.

5. Combining Combinators

You can mix combinators for complex selections.

Example:

div > p + span {
    text-decoration: underline;
}
CSS

This targets <span> that follows <p> inside <div>.

Conclusion

Combinators provide advanced element targeting, enabling cleaner and more efficient CSS code.

Leave a Reply