div内容溢出问题求助:已尝试text-align和overflow属性仍未解决
解决Div容器内容溢出问题
问题根源
你的.content元素是绝对定位,设置了width:100%同时加了padding:5px,但默认CSS盒模型是content-box,元素总宽度等于width + padding + border,这就导致.content实际宽度超出了父容器.container,引发横向溢出。另外vertical-align: center是无效值,正确写法是vertical-align: middle。
修复方案
- 给
.content添加box-sizing: border-box,让padding包含在width计算范围内,避免超出父容器; - 可选添加
overflow-wrap: break-word,确保长文本自动换行,彻底避免横向溢出; - 修正
vertical-align的错误值。
修改后的代码
CSS代码
body { font-family: Arial; font-size: 15px; } .container { position: relative; max-width: 1800px; height: auto; margin: 0 auto; text-align: center; width: 90%; } .container img { vertical-align: middle; /* 修正无效值 */ } .container .content { position: absolute; background: rgb(2, 2, 2); background: rgba(5, 5, 5, 0.5); /* 修正RGBA语法错误 */ color: rgb(255, 230, 0); width: 100%; padding: 5px; text-align: center; bottom: 0; overflow: hidden; box-sizing: border-box; /* 让padding包含在width内 */ overflow-wrap: break-word; /* 确保长文本自动换行 */ }
HTML代码
<div class="container"> <img src="https://pm1.narvii.com/6599/ca35b7330ff3ca028be95e4ff1e005ebe822b825_hq.jpg" alt="Bruce Lee" style="width:90%;"> <div class="content"> <h2>The Dragon</h2> <p>“Forget about winning and losing; forget about pride and pain. Let your opponent graze your skin and you smash into his flesh; let him smash into your flesh and you fracture his bones; let him fracture your bones and you take his life! Do not be concerned with escaping safely- lay your life before him!!”.</p> </div> </div>
额外说明
原代码中rgb(5, 5, 5, 0.5)是错误语法,半透明背景需用rgba(5,5,5,0.5),已一并修正。如果希望.content高度自适应内容且不被截断,可去掉overflow:hidden,但内容过多时会覆盖图片上方区域,此时可给.container设置min-height或根据图片高度调整。
内容的提问来源于stack exchange,提问作者Gunnar_Gray
相关产品推荐
相关产品推荐

