Combinators
Combinators are used in CSS to combine selectors and create more complex selections.
Let's review the combinators we've learned so far.
-
Type Combinator: Selects multiple types of elements.
- Example:
p, h1
CSSp,
h1 {
font-weight: bold;
} - Example:
-
Class Combinator: Selects elements with multiple classes.
- Example:
.my-class, .your-class
CSS.my-class,
.your-class {
color: blue;
} - Example:
-
Adjacent Sibling Combinator: Selects an element that is immediately preceded by a sibling element.
- Example:
p + h1
CSSp + h1 {
margin-top: 10px;
} - Example:
-
General Sibling Combinator: Selects all sibling elements that follow a specified element.
- Example:
p ~ h1
CSSp ~ h1 {
text-decoration: underline;
} - Example:
Combinator Code Example
<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>
.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:
-
All
<p>
and<h1>
elements will be bold. -
Elements with the
my-class
andyour-class
classes will be blue. -
The font size of elements with the IDs
my-id
andyour-id
is 24px. -
<h1>
elements immediately following a<p>
will have a top margin of 10px. -
All
<h1>
elements following a<p>
will have an underline.
Follow the emphasized portions of the code as you type it in.
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.