Combinator
A combinator allows you to combine CSS selectors to create more complex selectors.
Let's analyze combinators through the following example.
Code Example of Combinators
HTML
<body>
<p>First paragraph</p>
<h1>Heading 1</h1>
<h1 class="my-class">Heading 2</h1>
<p class="your-class">Second paragraph</p>
<div id="my-id">My ID</div>
<div id="your-id">Your ID</div>
</body>
CSS
.my-class {
color: red;
}
#my-id {
font-size: 24px;
}
p + h1 {
background-color: lightblue;
}
h1.your-class {
font-weight: bold;
}
#your-id {
text-decoration: underline;
}
In this example, the CSS is applied as follows:
-
my-class: The text color of elements with this class will be red.
-
#my-id: The font size of elements with this ID will be 24px.
-
p + h1: The
<h1>
that comes immediately after a<p>
will have a light blue background. -
h1.your-class: Among
<h1>
tags, elements with the classyour-class
will have bold text.
Try entering the parts emphasized with asterisks in the code.
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.