본문으로 건너뛰기

Combinators

Combinators

Combinators are a way to combine CSS selectors to create more complex selectors.

Let's review the combinators we've learned previously.


  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 the element that is immediately preceded by the former element.

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

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

Combinator Code Example

HTML
<body>
<p>First paragraph</p>
<h1>Title 1</h1>
<h1 class="my-class">Title 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 are displayed in bold.

  • Elements with the classes my-class and your-class are displayed in blue.

  • Elements with the IDs my-id and your-id have a font size of 18px.

  • The <h1> element that immediately follows a <p> has a top margin of 10px.

  • All <h1> elements that follow a <p> are underlined.


Follow the asterisk-highlighted part of the code to try inputting it.