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

Tailwind实现图片适配剩余空间:解决页面滚动问题

解决适配屏幕无滚动布局的图片缩放问题

要实现无滚动的自适应布局,核心是让图片所在容器的高度被父级约束,同时图片按比例缩放,不超出可用空间。直接修改你的代码即可实现:

<script src="https://cdn.tailwindcss.com"></script>

<div class="flex flex-col h-screen gap-2 p-2">
    <div class="flex gap-1 bg-orange-400 grow">
      <!-- 给图片容器添加h-full和overflow-hidden,限制高度不超出父级 -->
      <div class="relative w-3/5 h-full flex justify-center items-center bg-white overflow-hidden">
        <!-- 图片设置max-h-full、max-w-full和object-contain,保证按比例缩放且不超出容器 -->
        <img src="https://picsum.photos/800/1000" class="rounded-lg max-h-full max-w-full object-contain" />
        <span class="absolute m-4 bg-white">
          现在这个带图片的容器会自动缩放,不会超出底部红色区域了。
        </span>
      </div>
      <div class="w-2/5 flex flex-col rounded-lg border-2 border-slate-200">
        This is second child of the first child of root. The parent is set to grow and it should not grow beyond red box.
      </div>
    </div>
    <div class="flex flex-col p-1 bg-red-500 text-white">
      This is second child of the parent div which stays at bottom.
    </div>
  </div>

关键修改说明:

  • 给图片的父容器添加h-full:让它占满橙色容器的可用高度,而橙色容器的高度由根容器h-screen减去底部红色容器的高度自动计算,实现高度可变。
  • 添加overflow-hidden:防止图片超出容器时撑开布局。
  • 图片设置max-h-full max-w-full:限制图片的最大宽高不超过容器的宽高,保证缩放后不会超出。
  • object-contain:让图片保持原有宽高比完整显示在容器内,不会被裁剪(如果需要填充容器可以用object-cover)。

这样整个布局就会完全适配屏幕,不会出现滚动条,同时高度会根据底部红色容器的高度自动调整,图片也会自动缩放适配。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 07:18:19