设置z-index后卡片标题仍消失,技术问题求助
问题解决:卡片背景图覆盖标题的问题
问题原因
核心问题是**.index_title没设置定位属性**,导致你加的z-index:1完全不生效。背景图容器.index_img是块级元素,占满卡片宽高,标题默认在它下方被完全盖住;而.index_description设置了position:absolute,脱离文档流后z-index生效,所以能正常显示在背景图上方。
修复方案
给.index_title加上position:absolute,配合top:0和width:100%让它撑满卡片顶部,这样z-index就会生效,标题就能显示在背景图上方了。
修改后的完整代码
CSS代码
.index { width: 400px; height: 400px; background-color: white; float: left; margin-right: 30px; border-radius: 10px; overflow: hidden; position: relative; color: white; cursor: pointer; } .index_img { width: 100%; height: 100%; z-index: -1; } .index_html { background-image: url(web_image_html.jpeg); background-position: center; background-size: cover; z-index: -1; } .index a { color: #fff; text-decoration: none; } .index_title { text-align: center; font-family: 'Roboto', sans-serif; font-size: 30px; /* 新增定位属性,让z-index生效 */ position: absolute; top: 0; width: 100%; } .index_description { position: absolute; bottom: 0; left: 50%; transform: translateX(-50%); font-family: 'Inter', sans-serif; width: 100%; font-size: 18px; } .index_title, .index_description { background-color: rgba(82, 81, 81, 0.56); height: 80px; margin: 0; display: flex; align-items: center; justify-content: center; z-index: 1; } .index_html:hover { animation: index-animate 3s ease-in-out; } @keyframes index-animate { 0% { transform: scale(1); } 100% { transform: scale(1.3); } }
HTML代码
<div class="index"> <a href=""> <div class="index_img index_html"></div> <h2 class="index_title">HTML</h2> <p class="index_description">Lorem ipsum dolor sit amet.</p> </a> </div>
额外提示
z-index只对**设置了定位属性(position不为static)**的元素生效,这是你之前设置z-index没用的关键原因。给标题加定位后,就能和底部描述一样正常显示在背景图上层了。
内容的提问来源于stack exchange,提问作者ıLikeJavaButİtsKindaMessy
相关产品推荐
相关产品推荐

