Question

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?

Was it helpful?

Solution 3

.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;
}

OTHER TIPS

Try the following:

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

That is:

  • Select h2 elements...
  • ...which immediately follow a p element...
  • ...which is a child of an element with class container.

Since .container > p + h2 contains 1 class and 2 elements, it will override .container h2, which only has 1 class and 1 element.

This should work

.container p + h2 {
margin-top: 12px;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top