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

如何居中带固定宽度的div并解决文本溢出问题(父元素含GIF背景)

解决方案

问题根源

你给最内层的文本容器设置了固定百分比高度height:93.5%,这会强制容器高度不随内容变化,当窗口变窄文本换行后,内容高度超过容器固定高度就会溢出。另外,未将padding纳入宽度计算,可能导致小窗口下容器宽度额外超出。

修复步骤

  • 移除最内层div的height:93.5%,让容器高度随内容自动扩展
  • 给最内层div添加box-sizing: border-box,确保padding包含在宽度内,避免超出父容器
  • 保留.child-one上的min-height:600px,维持GIF背景的最小高度需求

修改后的代码

body {padding: 0; margin: 0;}

div#container-one {
 background: #eee;
 font-family: sans-serif;
 font-size: 20px;
 background-image: url('https://i.pinimg.com/originals/ef/2d/b0/ef2db0885d94fd149a4b7914923bb2a3.gif');
 background-position: center;
 background-repeat: no-repeat;
 background-color: #000;
}

div#container-one div.child-one {
 min-height: 600px;
 background-image: linear-gradient(180deg, rgb(70 70 70 / 60%), rgb(0 0 0 / 60%));
}

div#container-one div.child-one div {
 padding: 15px 20px;
 color: white;
 font-size: 25px;
 font-weight: bold;
 display: flex;
 flex-direction: column;
 align-items: center;
 place-content: center;
    
 width: 750px;
 max-width: 100%;
 margin: 0 auto;
 box-sizing: border-box; /* 让padding纳入宽度计算 */
}
<body>
<div id="container-one">
 <div class="child-one">
  <div>
   <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
   <p style="text-align:right;">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
   <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
  </div>
 </div>
</div>
</body>

效果说明

  • 窗口宽度大于750px时,文本容器保持750px宽度居中,父容器维持最小600px高度
  • 窗口宽度小于750px时,文本容器自适应宽度,高度随文本换行自动扩展,父容器高度也会跟着内容增加
  • 文本不会再溢出容器,同时GIF背景的最小高度需求也得到满足

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 03:17:08