You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用CSS实现网格卡片向全屏过渡的动画效果

解决卡片全屏切换的平滑过渡动画问题

要实现平滑过渡,核心是给卡片添加CSS过渡属性,并确保切换时变化的样式属性支持过渡效果。以下是修改后的完整代码:

JavaScript(无需修改)

const cards = $('.card');

cards.on("click", function () {
    $(this).toggleClass("fullscreen");
});

CSS(关键修改点)

.grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    grid-template-rows: repeat(3, 200px);
    position: relative;
    border: 1px solid black;
}

.card {
    box-sizing: border-box;
    margin: 10px;
    z-index: 1;
    background-color: #f3f3f3;
    padding: 20px;
    border-radius: 20px;
    border: 2px solid #ececec;
    overflow: hidden;
    /* 设置相对定位,为absolute定位提供基准 */
    position: relative;
    /* 添加过渡效果,指定需过渡的属性 */
    transition: top 0.3s ease, left 0.3s ease, width 0.3s ease, height 0.3s ease, z-index 0s;
}
        
.fullscreen {
    top: 10px;
    left: 10px;
    position: absolute;
    width: calc(100% - 20px);
    height: calc(100% - 60px); /* 替换bottom属性,确保height变化可过渡 */
    z-index: 2;
}

HTML(无需修改)

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="w-100">
    <div class="grid" id="cards">
        <div class="card">Widget 1</div>
        <div class="card">Widget 2</div>
        <div class="card">Widget 3</div>
        <div class="card">Widget 4</div>
        <div class="card">Widget 5</div>
        <div class="card">Widget 6</div>
    </div>
</div>

关键修改说明:

  • 给.card添加position: relative:将卡片从默认的static定位改为relative,让切换到absolute时的top/left变化有基准,能触发过渡。
  • 添加transition属性:明确指定要过渡的属性(top、left、width、height),z-index设为0s是因为层级变化无需过渡,瞬间生效即可。
  • 调整.fullscreen的height:把原bottom:50px改为height: calc(100% - 60px)(grid上下margin+原bottom值总和为10+50=60),避免bottom属性过渡效果不稳定的问题。

内容的提问来源于stack exchange,提问作者Onnwen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 07:35:11