skip to Main Content

I made a JSFiddle to reenact this problem.

I am trying to get a grid element to grow when hovered, but it causes this weird problem where it goes under the other grid element, then jumps to how I expected and want it to be.

Why does this happen and is there a way to get around it?

.container {
  height: 100vh;
  width: 100vw;
  display: grid;
  grid-template: 1fr / 1fr 1fr;
  margin: 1em;
  grid-gap: 1em;
}

.box {
  height: 100%;
  width: 100%;
  transition: width 0.5s;
}

.one {
  background: pink;
}

.two {
  background: red;
}

.box:hover {
  width: 60vw;
}
<div class="container">
  <div class="box one"></div>
  <div class="box two"></div>
</div>

2

Answers


  1. You can use flexbox with the flex short-hand property:

    .container {
      display: flex;
      gap: 1em;
      margin: 1em;
    }
    
    .box {
      flex: 1; /* This makes boxes take equal space by default */
      transition: 0.5s;
    }
    
    .box:hover {
      flex: 2; /* A hovered box expands twice as fast as a non-hovered */
    }
    

    Try it:

    .container {
      display: flex;
      gap: 1em;
      margin: 1em;
    }
    
    .box {
      flex: 1;
      transition: 0.5s;
    }
    
    .box:hover {
      flex: 2;
    }
    
    
    /* Demo only */
    
    body {
      margin: 0;
    }
    
    .container {
      height: 100vh;
    }
    
    .box {
      height: 100%;
    }
    
    .one {
      background: pink;
    }
    
    .two {
      background: red;
    }
    <div class="container">
      <div class="box one"></div>
      <div class="box two"></div>
    </div>
    Login or Signup to reply.
  2. I have wrote a detailed article about such effect that I invite you to read to understand how to achieve such effect using CSS grid: https://css-tricks.com/zooming-images-in-a-grid-layout/

    .container {
      height: calc(100vh - 2em);
      display: grid;
      grid-template-columns: auto auto;
      margin: 1em;
      gap: 1em;
    }
    .box {
      width: 0;
      min-width: 100%;
      transition: width 0.5s;
    }
    .box:hover {
      width: 40vw; /* read the article to understand the math behind setting this value */
    }
    
    .one {background: pink;}
    .two {background: red;}
    
    body {
      margin: 0;
    }
    <div class="container">
      <div class="box one"></div>
      <div class="box two"></div>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search