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

CSS Hovering to adjust text opacity doesnt work as intented, simplified as much as possible

i wanted to create divs where if you hover one side, the opposite text disappears. It works perfectly when hovering the left text, the right text disappears as expected but it doesnt work the other way around.

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>choose</title>
  <style>
    .right:hover~.left p {
      opacity: 0;
    }
    
    .left:hover~.right p {
      opacity: 0;
    }
  </style>
</head>

<body>
  <div class="container">
    <div class="left">
      <p>This is left text.</p>
    </div>
    <div class="right">
      <p>This is right text.</p>
    </div>
  </div>
</body>
</html>

this is the code as simplified as much as possible. Hovering one side should make the other text’s opacity to be zero, but it doesnt work both sides. I have tried a lot of different approaches to no avail.

Are there any explanations as to why this is happening? i figured it could be a .js or other css properties that could be interfering but its simplified to this point and it still doesnt work for me.

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

>Solution :

The ~ subsequent-sibling combinator only works forwards, but cannot work the other way around. What you want might be the :has() pseudo class.

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>choose</title>
  <style>
    .container:has(.left:hover) .right {
      opacity: 0;
    }
    
    .container:has(.right:hover) .left {
      opacity: 0;
    }
  </style>
</head>

<body>
  <div class="container">
    <div class="left">
      <p>This is left text.</p>
    </div>
    <div class="right">
      <p>This is right text.</p>
    </div>
  </div>
</body>
</html>
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