如何修改CSS使文本容器占图片80%宽度避免过早换行?
问题:如何让文本容器占据图片80%宽度并避免文本过早换行?
我计划使用如下代码,但不希望文本过早换行,希望文本容器能占据图片80%的宽度。请问需要修改哪些CSS属性来实现该效果?
原始代码
HTML
<h3>Hover over the image to see the effect.</h3> <div class="container"> <img src="https://walter.trakt.tv/images/movies/000/472/401/fanarts/thumb/ae10b31b1f.jpg.webp" alt="Avatar" class="image" style="width:100%"> <div class="textbox"> <div class="text">Each Christmas Eve, the Ghost of Christmas Present selects one dark soul to be reformed by a visit from three spirits. But this season, he picked the wrong Scrooge. Clint Briggs turns the tables on his ghostly host until Present finds himself reexamining his own past, present and future.</div> </div> </div>
CSS
.container { position: relative; width: 500px; } .image { opacity: 1; display: block; width: 100%; height: auto; transition: .5s ease; backface-visibility: hidden; } .textbox { transition: .5s ease; opacity: 0; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); -ms-transform: translate(-50%, -50%); text-align: center; } .container:hover .image { opacity: 0.3; } .container:hover .textbox { opacity: 1; } .text { background-color: #04AA5D; color: white; font-size: 15px; padding: 10px 10px; }
修改方案
只需对.textbox添加width: 80%属性即可实现需求:
- 由于
.container是相对定位,.textbox作为绝对定位元素,其宽度会基于容器(与图片宽度一致)的80%计算 - 原有
transform: translate(-50%, -50%)依然能让文本容器保持垂直水平居中,无需调整定位属性
若想进一步优化文本换行情况,还可酌情调整:
- 减小
.text的padding值,增加可用文本宽度 - 微调
font-size(注意平衡可读性)
修改后的完整CSS代码
.container { position: relative; width: 500px; } .image { opacity: 1; display: block; width: 100%; height: auto; transition: .5s ease; backface-visibility: hidden; } .textbox { transition: .5s ease; opacity: 0; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); -ms-transform: translate(-50%, -50%); text-align: center; width: 80%; /* 添加这一行 */ } .container:hover .image { opacity: 0.3; } .container:hover .textbox { opacity: 1; } .text { background-color: #04AA5D; color: white; font-size: 15px; padding: 10px 10px; }
内容的提问来源于stack exchange,提问作者mrsmith
相关产品推荐
相关产品推荐

