Home > Back-end >  Conditionals in css?
Conditionals in css?

Time:09-27

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> 

CodePudding user response:

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>

  • Related