css 为什么要从宽度转换:100%会导致过渡变得跳跃?

9gm1akwq  于 2023-06-07  发布在  其他
关注(0)|答案(2)|浏览(110)

我做了一个JSFiddle来重现这个问题。
我试图让一个网格元素在悬停时增长,但它导致了这个奇怪的问题,它在另一个网格元素下,然后跳到我所期望的和希望它是。
为什么会发生这种情况,有没有办法解决?

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

zbsbpyhn1#

你可以使用flexbox和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 */
}

试试看:

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

bsxbgnwa2#

我写了一篇关于这种效果的详细文章,我邀请你阅读以了解如何使用CSS网格实现这种效果: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>

相关问题