Codepen中Div高度过渡失效,段落与文本无过渡效果求助
卡片组件CSS过渡失效问题排查与修复
问题原因及修复方案
1. .text 高度过渡失效
CSS transition 不支持从 auto 到具体数值的高度过渡,必须明确初始高度值。
修复:
给 .text 设置初始具体高度(匹配标题默认高度),hover时修改为目标高度:
.text { /* 保留原属性,新增初始高度 */ height: 2rem; /* 替换auto为具体值 */ transition: height 0.5s ease; /* 简化transition写法 */ } .card:hover .text { height: 6rem; /* 根据需求调整目标高度,确保能容纳p标签 */ }
2. h3 位移过渡异常
hover时重复设置 position: absolute 属于冗余代码,且初始 bottom: 1rem 相对于 .text,hover时 bottom: 50vh 相对于视口,导致位移逻辑混乱;需保证过渡前后的属性值都是相对于同一父元素的具体数值。
修复:
移除hover时的冗余position属性,调整bottom值为相对于.text的数值:
.text h3 { /* 保留原属性,简化transition */ transition: bottom 0.5s ease; } .card:hover h3 { bottom: 3.5rem; /* 相对于.text底部的位移,根据.text目标高度调整 */ }
3. p 标签无过渡效果
display: none/block 是瞬时切换属性,不支持过渡动画,需改用 opacity 和 visibility 实现淡入效果。
修复:
.text p { position: absolute; bottom: 1rem; left: 1rem; color: white; margin: 0; opacity: 0; visibility: hidden; /* 隐藏时不占空间 */ transition: opacity 0.5s ease, visibility 0.5s ease; } .card:hover .text p { opacity: 1; visibility: visible; }
修改后的完整代码
HTML(无改动)
<div class="card"> <div class="text"> <h3>A Title</h3> <p>A Description for the story</p> </div> </div>
CSS
html, body { margin: 0; font-family: "Rubik", sans-serif; width: 100%; height: 100%; background: hsl(0, 0%, 10%); overflow: hidden; } .card { position: relative; background-image: url("/images/MyImage.png"); background-size: cover; width: calc(66vw - 4rem); height: 50vh; padding: 20px; border-radius: 1rem; margin: 2rem; overflow: hidden; } .text { background: black; box-shadow: 0 0 2rem 5rem black; position: absolute; left: 0; bottom: 0; height: 2rem; /* 替换auto为具体初始高度 */ width: 100%; /* 替换inherit为100%,避免继承padding问题 */ transition: height 0.5s ease; } .card:hover .text { height: 6rem; /* 调整为能容纳标题和描述的高度 */ } .text h3 { margin: 0; position: absolute; bottom: 1rem; left: 1rem; color: white; transition: bottom 0.5s ease; cursor: default; } .card:hover h3 { bottom: 3.5rem; /* 相对于.text底部的位移 */ } .text p { position: absolute; bottom: 1rem; left: 1rem; color: white; margin: 0; opacity: 0; visibility: hidden; transition: opacity 0.5s ease, visibility 0.5s ease; } .card:hover .text p { opacity: 1; visibility: visible; } h3::selection, p::selection { background: transparent; }
额外优化说明
- 把
.text的width: inherit改为width: 100%,避免继承.card的 padding 导致宽度超出; - 简化
transition属性写法,合并为单条声明更清晰。
内容的提问来源于stack exchange,提问作者dolfandds
相关产品推荐
相关产品推荐

