Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why Mouse Hovering over H1 doest not trigger CSS effect on H2 to start?

Given are two headings, Heading h1 and Heading h2.

The h2 has a nice underline effect set on her that shows on mouse over.

I would like to be able to hover on the h2 as well as h1, for the underline effect to start under h2 header.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The mouse over hover effect works when hovering over h2, but not when hovering over h1.

What is the reason that hovering over h1 does not trigger the underlining effect under h2?

h2:after {
    content: "";
    display: block;
    width: 10%;
    padding-top: 1em;
    border-bottom: 4px solid black;
    transition: 0.25s;
}

h2:hover:after{ /* Works as expected */
    width: 100%;
}

h1:hover h2:after{ /* Broken, does not trigger the h2 underline */
    width: 100%;
}
<a href="#" >
<hgroup>
<div>
    <div>
    <h1>Heading One</h1>
    </div>
</div>
</hgroup>
</a>



<h2>Heading Two</h2>

>Solution :

The way you’ve written your selector, its trying to target h2’s that are children of the h1, but your html structure doesn’t reflect that.

One option is to add a selector to the outer a and then target the adjacent h2 with the + adjacent sibling selector

Here’s a snippet showing that:

h2:after {
  content: "";
  display: block;
  width: 10%;
  padding-top: 1em;
  border-bottom: 4px solid black;
  transition: 0.25s;
}

h2:hover:after {
  /* Works as expected */
  width: 100%;
}

a:hover+h2:after {
  /* hover applied to the containing element so we can target the adjacent h2 */
  width: 100%;
}
<a href="#">
  <hgroup>
    <div>
      <div>
        <h1>Heading One</h1>
      </div>
    </div>
  </hgroup>
</a>



<h2>Heading Two</h2>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading