Why Gutenberg users should be using the adjacent sibling selector

If you are using Gutenberg for your blogs (as you should) then very quickly you will realise that sometimes when you add custom code or elements in your Gutenberg post, then things don't always have the right spacing compared with all of the other elements. Introducing, the adjacent sibling selector!

Example of a real problem

I love to add note-cards in my posts to highlight an important remark. These note-cards are simply custom HTML elements with my required code to achieve the card effect. However, whenever I add a note-card before or after a heading element, the spacing between the two elements are very different compared to all of the other elements by default. This is also the case when I add multiple custom HTML elements next to each other in Gutenberg. I don’t want to always manually fix the margins between the two as it is something I do not want to even worry about when writing a post – well here comes the adjacent sibling selector (combinator) to solve this!

Intro to the adjacent sibling selector (combinator)

The adjacent sibling selector (combinator) which is also known as element+element essentially considers two separate selectors and then targets the second element for the styling provided both elements are on the same level in the document flow – i.e. both elements are siblings (or share the same parent).

For example, if I had a header with a class of “header” followed by a sub-header element with a class of “sub-header” and wanted to always have a 16px margin between the two elements in all instances, then essentially the code will look something like this:

.header + .sub-header {
  margin-top: 16px;

Examples of a real solution

I utilise the above trick with my various cards and my h2’s. Here is a real example of my code:

.code-snippet + h2 {
  margin-top: 1.8rem;
.code-snippet + .code-snippet {
  margin-top: 1.6rem;
.note-card + .code-snippet {
  margin-top: 1.6rem;

To learn more about the adjacent sibling selector (combinator), check out the MDN Web Docs for it.

Let's talk.

Google reCaptcha: Invalid site key.