我做了一個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>
您可以使用具有flex速記屬性的flexbox:
.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>
我已經寫了一篇關于這種效果的詳細文章,我邀請你閱讀來理解如何使用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>