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>
>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>