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

如何让DaisyUI Drawer相对于容器div进行定位?

解决DaisyUI Drawer从主体右侧而非视口右侧滑入的问题

问题核心是默认DaisyUI Drawer的定位基于父容器的视口宽度,你将body设为500px居中后,Drawer的父容器(body)实际仍为视口宽度,导致抽屉从视口最右端弹出。要实现从主体右侧滑入,需调整结构和定位逻辑:

修改后的代码

HTML部分

<body>
  <div class="app-container">
    <h2>My App</h2>
    <div class="drawer drawer-end relative">
      <input id="my-drawer-4" type="checkbox" class="drawer-toggle" />
      <div class="drawer-content">
        <!-- Page content here -->
        <label for="my-drawer-4" class="drawer-button btn btn-primary">Open drawer</label>
      </div>
      <div class="drawer-side">
        <label for="my-drawer-4" aria-label="close sidebar" class="drawer-overlay"></label>
        <ul class="menu bg-base-200 text-base-content min-h-full w-80 p-4">
          <!-- Sidebar content here -->
          <li><a>Sidebar Item 1</a></li>
          <li><a>Sidebar Item 2</a></li>
        </ul>
      </div>
    </div>
  </div>
</body>

CSS部分

.app-container {
  max-width: 500px;
  margin-left: auto;
  margin-right: auto;
  font-family: sans-serif;
  position: relative;
}

:global(body) {
  margin: 0;
  padding: 0;
}

关键改动说明

  • 新增.app-container包裹所有内容:将原本给body的居中样式转移到这个容器上,确保Drawer的父容器是这个500px的居中容器
  • 给.drawer添加relative类:让Drawer的侧边栏(.drawer-side)基于这个500px的容器定位,而非整个视口
  • 保留drawer-end类:确保抽屉从容器右侧滑入,而非左侧

调整后,Drawer就会紧贴你500px的主体右侧滑入,而非从屏幕最右端弹出。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 13:55:13