Hide sibling divs on hover in CSS

I’m trying to create a CSS grid (or flex) where each item expands on hover while other items are hidden. I’m able to get the first item to work this way using :nthchild but obviously this nthchild doesn’t work with previous items in the grid.

<div class="container">

<div id="a" class="box">Div A Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</div>
<div id="b" class="box">Div B</div>
<div id="c" class="box">Div C</div>


</div>

CSS

.container {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-gap: 20px;
  margin: 20px;
}
 
.box {
   background-color: grey;
   padding: 20px;
}
  
#a:hover {
     grid-column: 1 / 4;
}
 
#a:hover ~ :nth-child(-n+8) {
  display: none;
}

#b:hover {
     grid-column: 1 / 4;
}
 
#b:hover ~ :nth-child(-n+8) {
  display: none;
}

Here’s the code on jsfiddle:
https://jsfiddle.net/ktz8qdcp/20/

Appreciate your help!

56 thoughts on “Hide sibling divs on hover in CSS”

Leave a Comment