DriftingSteps
DriftingSteps

Reputation: 526

(SCSS) Changing properties of preceding element based on the state of succeeding element

I have the following setup in HTML and SCSS -

h1 {
  margin-bottom: 24px;
  + p {
    margin-top: 0;
  }
}
p {
  margin-bottom: 24px;
}
<h1>Main title</h1>
<p>Sub-title goes there here</p>

What I'm trying to achieve is, I want <h1>'s margin-bottom to change from 24px to 0px when there's <p> tag after it, but if there's no <p> tag, then the margin-bottom in <h1> will remain 24px.

I tried using & operator but I can't seem to get my head around it.

h1 {
  margin-bottom: 24px;
  & + {
    margin-bottom: 0;
  }
  + p {
    margin-top: 0;
  }
}
p {
  margin-bottom: 24px;
}

What do you think I should do? Do I need to use @if directive for this certain case?

Upvotes: 1

Views: 596

Answers (1)

Hidden Hobbes
Hidden Hobbes

Reputation: 14183

This is not possible due to the way CSS works

What you are looking to achieve is ultimately not possible. SASS compiles into CSS which is only traversed it one direction. This means you can target elements which are preceded by another element but you cannot select elements that are succeeded by another element.

What can you do?

Given this restriction the most suitable way of achieving your result would be to change the logic so that the margin-bottom on the h1 is replaced with margin-top on the p tag.

SASS

h1 {
  margin-bottom: 0;
  + p {
    margin-top: 0;
  }
}
p {
  margin-top: 24px;
}

Compiled example

h1 {
  margin-bottom: 0;
}
h1 + p {
  margin-top: 0;
}
p {
  margin-top: 24px;
}
<h1>Main title</h1>
<p>Sub-title goes there here</p>

If you can't move the margin from the h1 to the p tag it would be acceptable to use a negative margin-top on the p to offset the margin-bottom on the h1.

SASS

h1 {
  margin-bottom: 24px;
  + p {
    margin-top: -24px;
  }
}
p {
  margin-top: 24px;
}

Compiled example

h1 {
  margin-bottom: 24px;
}
h1 + p {
  margin-top: -24px;
}
p {
  margin-top: 24px;
}
<h1>Main title</h1>
<p>Sub-title goes there here</p>

Upvotes: 2

Related Questions