如何让文本适配div容器?解决div文本溢出问题
解决文本溢出容器的问题
我正在给链接设置样式,想要达到预期效果,但第二个div里的文本溢出了容器。
当前效果:
预期效果:
相关代码
JavaScript
var div_color = document.getElementsByClassName('div-categoria'); console.log div_color[0].style.backgroundColor = '#7d35ed'; div_color[1].style.backgroundColor = '#e93f3f'; div_color[2].style.backgroundColor = '#e4bf2a';
CSS
.categoria{ margin: 2.5rem 0; } .div-categoria{ display: inline-flex; height: 120px; width: 120px; border-radius: 10px; transition: transform .2s; margin-right: 20px; position: relative } .div-categoria:hover{ transform: scale(1.10); } .categoria a{ text-decoration: none; color: white; } .div-categoria p { margin: 0; color: black; position: absolute; top: 50%; left: 50%; margin-right: -50%; transform: translate(-50%, -50%); text-transform: uppercase; font-size: 25px; }
HTML
<div class="categoria"> <a href="#link"><div class="div-categoria"><p>Comida</p></div></a> <a href="#link"><div class="div-categoria"><p>Bebidas Alcoolicas</p></div></a> <a href="#link"><div class="div-categoria"><p>Bebidas</p></div></a> </div>
解决办法
问题出在绝对定位的<p>元素没有宽度限制,加上字体过大,长文本直接溢出容器。可以通过以下调整修复:
- 改用flex布局实现文本居中,替代绝对定位,让文本自动继承容器宽度
- 给
<p>添加换行规则,限制宽度 - 调整字体大小适配容器
修改后的CSS:
.categoria{ margin: 2.5rem 0; } .div-categoria{ display: inline-flex; height: 120px; width: 120px; border-radius: 10px; transition: transform .2s; margin-right: 20px; /* flex居中 */ justify-content: center; align-items: center; text-align: center; } .div-categoria:hover{ transform: scale(1.10); } .categoria a{ text-decoration: none; color: white; } .div-categoria p { margin: 0; color: black; text-transform: uppercase; /* 限制宽度,避免贴边 */ width: 90%; /* 长单词自动换行 */ word-wrap: break-word; /* 调整字体大小适配容器 */ font-size: 18px; }
修改后,长文本会自动换行并居中显示,完美匹配预期效果。
内容的提问来源于stack exchange,提问作者xSkolz
相关产品推荐
相关产品推荐

