Search code examples
cssparent-childdescendant

CSS: Adjacent sibling inside a class


Trying to add a top-margin to an adjacent sibling.

<div class="container">
  <h2>Header 1</h2>
  <p>Some text and sentences...</p>
  <h2>Header 2</h2>
  <p>Some more text and sentences..</p>
</div>

Normally I would accomplish top-margin on "Header 2" by using css on the adjacent siblings.

p + h2{
  margin-top: 12px;
}

However, h2 has margin defined via

.container h2{
  margin: 24px 0px;
}

How can I make the adjacent siblings css work while overriding the .container h2 css?


Solution

  • .container h2 is more specific than p + h2 so it is taken into consideration. You need a more specific selector to override the margin.

    This should be "more specific" and override:

    .container p + h2 {
        margin-top: 12px;
    }