peter flanagan
peter flanagan

Reputation: 9830

hide an element on hover css that is not a direct child

There is a gap in my css knowledge here. I am trying to hide an element when another element is hovered on using styled-components.

const InnerBox = styled.div`
   background: green;
   height: 20px;
   width: 20px;
   margin: 0 auto;
`

const BoxTwo = styled.div`
   height: 40px;
   width: 40px;
   background: red;
`

const Box = styled.div`
   height: 40px;
   width: 40px;
   background: pink;
   // This works as InnerBox is in Box
   &:hover ${InnerBox} {
     display: none; 
   }
   // This doesn't work as BoxTwo is not in Box
   &:hover ${BoxTwo} {
     display: none; 
   }
`

My jsx looks like this:

<BoxTwo />
<Box>
    <InnerBox />
</Box>
<BoxTwo />

Does anyone know how to target the two BoxTwo from the hover on Box?

It looks like it is not possible. I can target the one after, but not the one before

Upvotes: 0

Views: 317

Answers (1)

Arkellys
Arkellys

Reputation: 7811

You can use the + selector:

#innerBox {
   background: green;
   height: 20px;
   width: 20px;
   margin: 0 auto;
}

#boxTwo {
   height: 40px;
   width: 40px;
   background: red;
}

#box {
   height: 40px;
   width: 40px;
   background: pink;
}

#box:hover #innerBox,
#box:hover + #boxTwo {
  display: none; 
}
<div id="box">
  <div id="innerBox"></div>
</div>
<div id="boxTwo"></div>

In your case it will be:

&:hover + ${BoxTwo} {
  display: none; 
}

The + selector will only work when the element (BoxTwo) is placed immediately after the parent selector (Box).

Upvotes: 2

Related Questions