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

如何实现CSS div自适应内容 移除h-screen适配绝对定位偏移元素

解决方案

你遇到的核心问题是inner元素设置position: absolute后脱离了文档流,父容器无法感知其高度,直接移除h-screen会出现高度塌陷,按以下方案操作即可:

方案1:保留absolute定位(适合必须用绝对定位的场景)

  • 直接删除section#home的class属性里的h-screen类
  • 给右栏的outer容器手动设置最小高度匹配图片最大高度,避免高度塌陷,给outer添加min-h-[580px]类即可(Tailwind CSS v2版本可自定义类加CSS规则min-height: 580px)
  • 你已经给outer加了overflow-x: hidden,可以正常挡住超出内容,不会出现横向滚动条

方案2:替换absolute为负边距(更推荐,完全自适应高度)

不需要手动写死高度,直接把绝对定位改为负外边距,元素保留在正常文档流中,父容器可以自动适配内容高度:

  1. 调整inner的CSS规则,移除绝对定位相关属性,替换为负右外边距:
.inner{
    margin-right: -172px;
}
  1. 删除section#home的class属性里的h-screen类即可
    该方案既保留了图片向右偏移172px的视觉效果,又能让整个home区块自动适配左右两栏的最高内容高度,不会出现高度塌陷问题。

核心修改后代码示例

<section id="home" class="main lg:pl-28 flex flex-wrap flex-row w-full">
    <div class="flex flex-col w-full lg:w-5/12 justify-center lg:pr-28 bg-green-200">
        <p class="text-lg mb-0 text-gray-600">Title 1</p>
        <h1 class="mb-4 text-3xl md:text-5xl font-bold leading-tight text-center md:text-left slide-in-bottom-h1">Title 2</h1>
        <p class="leading-normal text-base md:text-2xl mb-8 text-center md:text-left slide-in-bottom-subtitle">Title 3</p>
    </div>
    <div class="outer w-full lg:w-7/12 overflow-x-hidden relative flex items-center bg-red-200">
        <div class="flex gap-4 inner">
            <div class="flex-initial img-container">
                <img src="https://via.placeholder.com/345x580" class="hero-img">
            </div>
            <div class="flex-initial img-container">
                <img src="https://via.placeholder.com/345x580" class="hero-img">
            </div>
            <div class="flex-initial img-container">
                <img src="https://via.placeholder.com/345x580" class="hero-img">
            </div>
        </div>
    </div>
</section>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 04:30:04