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

Time:05-31

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.

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>

CodePudding user response:

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>

CodePudding user response:

h1:hover h2 selector requires h2 to be the child of the h1. You can apply hover styles only for descendants elements.

CodePudding user response:

Since the h2 isnt nested into the h1 you cant access it in css. Adding a bit of javascript does the trick.

const h1 = document.querySelector('h1');
const h2 = document.querySelector('h2');

h1.addEventListener('mouseenter', () => {
  h2.classList.add('active');
})
h1.addEventListener('mouseout', () => {
  h2.classList.remove('active');
})
    h2:after {
        content: "";
        display: block;
        width: 10%;
        padding-top: 1em;
        border-bottom: 4px solid black;
        transition: 0.25s;
    }

    h2:hover:after,h2.active:after { /* Works as expected */
        width: 100%;
    }
<a href="#" >
<hgroup>
<div>
    <div>
    <h1>Heading One</h1>
    </div>
</div>
</hgroup>
</a>

<h2>Heading Two</h2>

  • Related