Skip to main content
Practice

Combinators

Combinators are used in CSS to combine selectors and create more complex selections.

Let's review the combinators we've learned so far.


  1. Type Combinator: Selects multiple types of elements.

    • Example: p, h1
    CSS
    p,
    h1 {
    font-weight: bold;
    }
  2. Class Combinator: Selects elements with multiple classes.

    • Example: .my-class, .your-class
    CSS
    .my-class,
    .your-class {
    color: blue;
    }
  3. Adjacent Sibling Combinator: Selects an element that is immediately preceded by a sibling element.

    • Example: p + h1
    CSS
    p + h1 {
    margin-top: 10px;
    }
  4. General Sibling Combinator: Selects all sibling elements that follow a specified element.

    • Example: p ~ h1
    CSS
    p ~ h1 {
    text-decoration: underline;
    }

Combinator Code Example

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:

  • All <p> and <h1> elements will be bold.

  • Elements with the my-class and your-class classes will be blue.

  • The font size of elements with the IDs my-id and your-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.