CSS hover affects another element with pseudo after attribute

Viewed 36

This following css works (it makes visible button2 when hovering on button1)

#btn1:hover ~ #btn2 { visibility: initial;}

But if I want to make the same for the pseudo element #btn2:after, the following code doesn't work

#btn1:hover ~ #btn2:after { visibility: initial;}

Is there a reason or a workaround for it ?

3 Answers

It could be that you need to add the content property to btn2

#btn1:hover ~ #btn2 { 
  visibility: initial;
  background-color:red
}
#btn1:hover ~ #btn2:after{
  visibility: initial;
  content:' Soy el after';
}
<button id="btn1">Botón 1</button>
<button id="btn2">Botón 2</button>

You can also use display:none;

When you use visibilty:hidden; your buttons will still have width and height in your body element but when using display:none; you can place any element to that position.

body {
  position: relative;
  height: 100vh;
  background-color: bisque;
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
  gap:1rem;
}
button{
  height: 50px;
  width:100px;
}

#btn2::after{
  content: '';
  width:20px;
  height: 20px;
  background-color: red;
  display: none;
}

#btn1:hover ~ #btn2::after {
   display: inline-block;
}
<button id="btn1">btn1</button>
<button id="btn2">btn2</button>

Obviously you are both right. I made some adjustments and it works... can't figure what was wrong

I used visibility parameter

Related