1

Is it possible to use some form of conditionals?

Building a new design style out in code.

Usually the <h1> tag has a small line underneath it. The <h2> tag does as well but when the <h1> is present the <h2> tag should not have a line underneath it.

h1:after {
    display: block;
    content: "";
    background-color: green;
    height: 3px;
    border-radius: 6px;
    width:50px
}

h2:after {
    display: block;
    content: "";
    background-color: orange;
    height: 3px;
    border-radius: 6px;
    width:30px
}
<h1>H1 title</h1> 

<h2>So now this H2 title should not have a line since there is a h1 above it.</h2> 

1
  • 2
    You can use the selector h1 + h2:after Commented Sep 27, 2021 at 10:16

1 Answer 1

6

You can use the general sibling combinator ~ for this, as long as both headings share the same parent element.

If you only want the h2 that directly follows the h1 to not have it, use the adjacent sibling combinator + instead.

Please note that :after is old CSS 2.1 syntax. Please use CSS3's ::after instead.

h1::after {
  display: block;
  content: "";
  background-color: green;
  height: 3px;
  border-radius: 6px;
  width: 50px
}

h2::after {
  display: block;
  content: "";
  background-color: orange;
  height: 3px;
  border-radius: 6px;
  width: 30px
}

h1~h2::after {
  display: none;
}
<div>
  <h1>H1 title</h1>

  <h2>So now this H2 title should not have a line since there is a h1 above it.</h2>
</div>

<div>
  <h2>So now this H2 title should have a line since there is no h1 above it.</h2>
</div>

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, and how can i do that when they are not in the same parent element?
@Lucas With CSS means only, you cannot. You'd have to apply classes then. It cannot be achieved based on markup structure alone then.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.