Reputation: 526
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 24p
x 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
Reputation: 14183
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.
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.
h1 {
margin-bottom: 0;
+ p {
margin-top: 0;
}
}
p {
margin-top: 24px;
}
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
.
h1 {
margin-bottom: 24px;
+ p {
margin-top: -24px;
}
}
p {
margin-top: 24px;
}
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