如何调整CSS使图片悬浮覆盖层(overlay)内的文字适配矩形框
图片覆盖层文字适配调整方案
问题原因
- 父容器
.cont未设置相对定位,导致覆盖层的绝对定位基准错误,易出现尺寸和图片不匹配的问题 - 外层
overlay元素错误添加了text类,和内部文字容器的定位规则冲突 - 内部文字容器未限制宽度,也没有设置内边距,文字默认会尽可能横向展开超出覆盖层边界
- 未设置长文本的溢出处理规则
调整方案
1. 修正CSS规则
/* 给父容器加相对定位,作为覆盖层的定位基准 */ .cont { position: relative; display: inline-block; /* 让容器尺寸和内部图片保持一致 */ } .overlay { position: absolute; top: 0; bottom: 0; left: 0; right: 0; height: 100%; width: 100%; opacity: 0; transition: .5s ease; background-color: blue; } .cont:hover .overlay { opacity: 1; } .text { color: gold; font-size: 10px; position: absolute; top: 50%; left: 50%; -webkit-transform: translate(-50%, -50%); -ms-transform: translate(-50%, -50%); transform: translate(-50%, -50%); text-align: center; /* 新增适配规则 */ width: 90%; /* 限制文字容器宽度,左右各预留5%边距 */ padding: 0 8px; /* 额外增加左右内边距避免文字贴边 */ box-sizing: border-box; /* 内边距不会撑大容器宽度 */ max-height: 100%; /* 限制高度不超过覆盖层 */ overflow-y: auto; /* 文字过长时纵向滚动,也可改为overflow-y: hidden直接隐藏溢出部分 */ word-wrap: break-word; /* 长单词自动换行 */ }
2. 修正HTML类名错误
把所有overlay元素上多余的text类删除,修改后结构如下,所有article块统一按照该结构调整即可:
<article class="box box9"> <div class="cont"> <img src="images/Me 2.jpg" height="200px" alt="Community Program Coordinator and Interim Communications Director for the United Minority Media Association. " class="image"> <!-- 移除了overlay元素上的text类 --> <div class="overlay"> <div class="text">Ruby Watson is the Community Program Coordinator and Interim Communications Director for the United Minority Media Association. Since 2000, She has worn many hats with this organization. She was the Recording Secretary, Publicist, and National Newsletter/Magazine Editor of UMMA Media News for the United Minority Media Association. She also serves on the Time Well Spent Committee and UMMA KC Watch and is working with our web developer for the ummahqkc1.org website. Ruby has a Bachelor’s in Communications and a Master of Liberal Arts degree. While working on her undergraduate degree, she interned as the Assistant Producer for the Walt Bodine Show, KCUR 89.3 AM, and as production interns for KKFI 90.1 FM and Kansas City Public Television station where she worked closely with Nick Haines, Executive Producer of Public Affairs/News.</div> </div> </div> <h2>Ruby Watson, Interim Vice President of Communications</h2> </article>
内容的提问来源于stack exchange,提问作者Scott Owen
相关产品推荐
相关产品推荐

