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

如何实现父flex容器中左侧div滑入效果并让右侧div自适应?

实现左侧Div滑入+右侧自适应布局的解决方案

要搞定左侧div从左滑入、右侧自动调整位置的效果,不用复杂操作,靠CSS过渡+状态类就能实现流畅动画,结合Bootstrap的flex布局特性刚好适配你的需求。下面一步步改代码:

1. 调整CSS,加过渡和初始隐藏状态

原来的左侧div默认显示,我们让它一开始藏在视口左边,用过渡实现滑入;同时给右侧div加过渡,让它的宽度变化更顺滑:

html,
body {
  height: 100%;
  font-family: "Poppins", sans-serif;
  margin: 0; /* 清掉默认边距,避免出现不必要的滚动条 */
}

.brand {
  font-family: "Rock Salt", sans-serif;
}

.leftside {
  width: 50%;
  height: 100%;
  padding: 2rem;
  overflow-y: scroll;
  overflow-x: hidden;
  background-color: #DEE2E6;
  transform: translateX(-100%); /* 初始状态:完全移出左侧视口 */
  transition: transform 0.5s ease-in-out; /* 0.5秒滑入,ease-in-out让动画开头结尾慢、中间快,更自然 */
  flex-shrink: 0; /* 固定宽度,不让flex布局压缩它 */
}

.rightside {
  width: 100%; /* 初始占满整个容器,左侧滑入后自动被挤到50% */
  height: 100%;
  padding: 2rem;
  background-color: #F8F9FA;
  transition: width 0.5s ease-in-out; /* 宽度变化也加过渡,避免生硬跳变 */
}

/* 滑入状态类:添加这个类就会触发滑入动画 */
.leftside.slide-in {
  transform: translateX(0);
}

.leftside::-webkit-scrollbar {
  display: none;
}

2. 修改HTML,加触发按钮

不用大改结构,给右侧加个按钮用来触发滑入效果,方便测试:

<div class="d-flex" style="width: 100%;height: 100%;">
  <!-- 初始不要加slide-in类,保持隐藏状态 -->
  <div class="leftside">
    <div class="card" style="width: 100%;">
      <div class="card-body">
        <h5 class="card-title">Product title</h5>
        <h6 class="card-subtitle mb-2 text-body-secondary">$50</h6>
        <p class="card-text">Some quick example text to build on the product title and make up the bulk of the card's content.</p>
      </div>
    </div>
  </div>
  <div class="rightside">
    <!-- 点击这个按钮触发滑入 -->
    <button onclick="slideInLeft()" class="btn btn-primary mb-3">滑入左侧面板</button>
    <div class="card" style="width: calc(50% - 4rem);position: absolute; bottom: 2rem;">
      <div class="card-body">
        <h2 class="card-title"><span id="brand">Store Name Here</span></h2>
        <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p>
      </div>
    </div>
  </div>
</div>

3. 写JS触发函数

就几行代码,给左侧div加上滑入的状态类就行:

function slideInLeft() {
  const leftDiv = document.querySelector('.leftside');
  // 防止重复点击重复触发
  if (!leftDiv.classList.contains('slide-in')) {
    leftDiv.classList.add('slide-in');
  }
}

关键说明

  • 用transform: translateX()做滑入,比改width或position性能好太多,不会触发页面重排,动画更流畅。
  • 右侧初始设100%宽度,利用Flex的自动布局,左侧滑入后会自动把右侧挤到剩下的50%,加过渡后这个变化就很顺滑。
  • flex-shrink:0保证左侧div不会被压缩,始终保持50%的宽度。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 01:15:24