C

CSS Tutorial

Clean • Professional

CSS Combinators

2 minute

CSS Combinators

When working with CSS, we often need to select elements based on their relationship with other elements in the HTML structure. That’s where CSS combinators come into play.

A combinator defines the relationship between two or more selectors. Instead of targeting elements individually, combinators allow you to style elements based on hierarchy, parent-child relationships, or sibling connections.

There are four main types of CSS combinators:

learn code with durgesh images​​​​​​​

Let’s explore each with examples and use cases.

Descendant Selector (space)

The descendant selector targets all elements inside another element, no matter how deeply they are nested. If an element is within a parent—even if it’s several layers deep—it will be selected.

Why use it?

  • When you want to apply a consistent style to all elements inside a specific container.
  • Useful for styling all links in a navigation bar or all paragraphs inside an article section.

Example:

div p {
  color: blue;
}

Child Selector (>)

The child selector is more specific. It selects only the direct children of a parent, ignoring nested elements further inside.

Why use it?

  • When you only want to style immediate elements and not affect nested content.
  • Perfect for designing menus, lists, and layouts where nested items need different styling.

Example:

div > p {
  color: green;
}

Adjacent Sibling Selector (+)

This selector targets the first element that comes immediately after another element, as long as they share the same parent.

Why use it?

  • Great for styling captions, notes, or special content that directly follows a heading.
  • Often used to add spacing or design emphasis after titles or labels.

Example:

h1 + p {
  color: red;
}

General Sibling Selector (~)

The general sibling selector targets all elements that are siblings of a specified element and come after it. Unlike the adjacent sibling, this applies to every matching sibling, not just the first.

Why use it?

  • Useful when you want to apply consistent styling to all elements that follow a specific element.
  • Example: All paragraphs after a heading, all checkboxes after a label, or all list items after a particular marker.

Example:

h1 ~ p {
  color: orange;
}

Flowchart - CSS Combinators

learn code with durgesh images

 

Article 0 of 0