Comprehensive Training on CSS Combinators

css combinators tutorial
10 November 2024

Understanding CSS Combinators

When you work with styling in CSS, one of the important and interesting topics is how to select elements for styling with the help of CSS Combinators. These combinators give you the ability to target elements without the need to add extra classes, simply by utilizing HTML structure to effectively aim at elements. If you want to select similar elements like siblings of a specific element, CSS Combinators precisely provide what you need.

There are four types of combinators in CSS: descendant combinator (space ..), child combinator (.. > ..), adjacent sibling combinator (.. + ..), and general sibling combinator (.. ~ ..). Each of these has its specific uses and can assist you in different scenarios. Understanding the concept of each of these combinators can lead to simpler coding and managing styles.

In the descendant combinator, which is shown with a space, you can select all elements that are inside another element. Assume you have a div that contains multiple p tags; by using the descendant combinator, you can select all those p tags.

The child combinator, indicated with the > symbol, only allows you to select direct children of an element. For instance, if you have a div and within it another element, using this combinator allows you to target only the first p tag inside it.

The adjacent sibling combinator and general sibling combinator are also used for selecting elements that are on the same level. The adjacent sibling combinator only selects the element right after a target element, while the general sibling combinator selects any element that comes after the target element on the same level.

Now let’s take a look at practical examples to better understand the application of each.

Practical Examples with CSS Combinators

<style>
div p {
color: blue;
}

div > p {
font-weight: bold;
}

h2 + p {
background-color: yellow;
}

h2 ~ p {
color: red;
}
</style>

<div>
<p>This is a paragraph inside a div.</p>
<section>
<p>Another paragraph, but nested in a section.</p>
</section>
</div>

<h2>Heading 2</h2>
<p>Paragraph right after h2.</p>
<p>Another paragraph, not immediately after h2.</p>
<p>One more paragraph.</p>

Line-by-Line Explanation of the Code

div p: This selector targets all p tags that are inside each div, allowing you to change their text color to blue.
div > p: This selects only the direct child p of a div, like the first p tag, and makes it bold.
h2 + p: This targets the first p that immediately follows an h2, giving it a yellow background.
h2 ~ p: This selector targets any p that comes after an h2 on the same level, changing its color to red.

FAQ

?

How can I use combinators in CSS?

?

What is the difference between descendant and child combinators?

?

What is the difference between adjacent sibling and general sibling combinators?

?

What is the practical use of CSS combinators?