图片Crossfade hover效果遮挡文本,如何将文本置于图片下方?
问题与解决方案
问题描述
实现两张图片hover时的淡入淡出切换效果,功能正常,但文本被图片遮挡,需要让文本位于图片下方而非后方。
原代码
CSS代码
#center { text-align: center; } #under { text-align: center; margin: 0; max-width: 50%; margin-left: auto; margin-right: auto; } #crossfade { position: relative; } #crossfade img { position: absolute; left: 0; opacity: 1; -webkit-transition: opacity 0.5s ease-in-out; -moz-transition: opacity 0.5s ease-in-out; -o-transition: opacity 0.5s ease-in-out; -ms-transition: opacity 0.5s ease-in-out; transition: opacity 0.5s ease-in-out; } #crossfade img.top:hover { opacity: 0; } img { margin-right: 3%; max-width: 65% } #goofy { margin: 0; margin-bottom: 40px; }
HTML代码
<div id="center"> <div id="crossfade"> <img id="goofy" src="https://inpulse.eli328.repl.co/half.png" alt="half" class="bottom"> <img id="goofy" src="https://inpulse.eli328.repl.co/active.png" alt="active" class="top"> </div> <p id="under"> The Inpulse creates a powerful electric charge that when reaching sufficient levels, creates a bright arc of lightining between the two prongs. The handheld device will definitely satisfy its user. </p> </div>
修复方法
问题根源:图片使用position: absolute后脱离文档流,导致父容器#crossfade高度塌陷,文本占据原本图片的位置,被绝对定位的图片覆盖。
方案一:修复父容器占位(推荐)
给父容器设置宽度和宽高比,让它撑起图片的占位空间,同时保持响应式:
- 调整
#crossfade的CSS:
#crossfade { position: relative; display: inline-block; /* 让容器宽度适配内容 */ width: 65%; /* 和图片max-width保持一致 */ aspect-ratio: 4/3; /* 根据你的图片实际宽高比调整,比如16/9、4/3等 */ }
如果需要兼容旧浏览器,可用padding-top替代aspect-ratio,比如4:3比例对应padding-top: 75%;(3÷4×100%)。
- 调整图片的定位与样式,同时修复HTML中重复的id(id必须唯一):
#crossfade img { position: absolute; top: 0; left: 0; width: 100%; /* 填满父容器 */ height: 100%; /* 填满父容器 */ object-fit: contain; /* 保持图片比例,避免拉伸 */ opacity: 1; transition: opacity 0.5s ease-in-out; } .goofy { margin: 0; margin-bottom: 40px; }
<div id="crossfade"> <img class="goofy bottom" src="https://inpulse.eli328.repl.co/half.png" alt="half"> <img class="goofy top" src="https://inpulse.eli328.repl.co/active.png" alt="active"> </div>
方案二:无需绝对定位(更简单)
用相对定位让两张图片叠加,父容器会自动根据图片高度撑开:
#crossfade { display: inline-block; width: 65%; } #crossfade img { position: relative; display: block; width: 100%; margin-bottom: -100%; /* 实现图片重叠 */ opacity: 1; transition: opacity 0.5s ease-in-out; } #crossfade img.top:hover { opacity: 0; }
同时记得修复HTML中重复的id问题。
内容的提问来源于stack exchange,提问作者user19081214
相关产品推荐
相关产品推荐

