Home > Software engineering >  How to acces pseudo element(s) when its sibling is hovered
How to acces pseudo element(s) when its sibling is hovered

Time:11-07

I have this html code :

<div class="content">
   <h2><a href="#">Hero</a></h2>
   <h2>Hero</h2>
    <div class ="tricky"></div>
 </div>

where content is a flex container;tricky is another flex container with pseudo elements before and after that i want to use for effects when a is hover.(meaning i got .tricky::before{...} and .tricky::after{..} ) tricky , tricky::before , tricky::after all of them are square width visibility:hidden

I want when a is hover to affect all tricky`s visibility to visible or any other change(ex: color/width/height anything) or one at a time(ex: .content a:hover ~.tricky:before{...} I tried : content a:hover ~(or ).tricky:before { ...} ; content a :hover ~(or )*{...} and no method works. Any help? Thank you.

CodePudding user response:

Do you want this? .tricky::after will show on h2's Hover

   //CSS 
        <style> 
                h2:hover   .tricky::after{
                    content: "123";
                }
        </style>
     
     //HTML
       <div class="content">
         <h2><a href="#">Hero</a></h2>
         <h2>Hero</h2>

         <div class ="tricky"></div>
      </div>

CodePudding user response:

I have used onmouseover and onmouseleave event listener to track the hover and out event and added/removed the visibleAfter class which will take care of the styling of content::after in the CSS

const link = document.getElementById('link');
const tricky = document.getElementById('tricky');

link.addEventListener('mouseover', ()=>{
  tricky.classList.add('visibleAfter')
})

link.addEventListener('mouseleave', ()=>{
  tricky.classList.remove('visibleAfter')
})
.tricky, .tricky::before, .tricky::after {
  width: 50px;
  aspect-ratio: 1;
  background: #777;
  position:relative;
}

.tricky::before, .tricky::after{
  content: '';
  display:block;
  position:absolute;
  display:block;
  visibility:hidden;
}

.tricky::before{
  top:.5em;
  left:.5em;
  background:red;
}

.tricky::after{
  top: 1em;
  left:1em;
  background:green;
}

.visibleAfter::after {
  visibility: unset;
}
<div class="content">
   <h2><a id='link' href="#">Hero</a></h2>
   <h2>Hero</h2>
    <div id='tricky' class="tricky"></div>
 </div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related