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