如何通过CSS阴影实现B、C标签视觉上位于A标签后方?
实现标签页的层级阴影效果
问题描述
现有一套HTML/CSS实现的标签页,当前所有标签处于同一视觉层级,希望让B、C标签上方出现阴影,呈现出位于A标签后方的视觉效果。
解决方案
要实现这个效果,核心是通过**层级控制(z-index)和阴影(box-shadow)**结合,调整标签的堆叠顺序并添加顶部阴影模拟后方效果:
- 给所有标签设置默认层级,让第一个标签层级更高,压在其他标签上方
- 给非第一个标签添加顶部阴影,模拟被遮挡的视觉感
- 调整标签的伪元素层级,避免伪元素遮挡前面的标签
修改后的完整代码
CSS代码
body { background-color: rgb(245, 165, 61); --border-rad: 5px; } .wrapper { width: 80vh; margin: 5%; } .tabs { display: flex; justify-content: space-around; } .tab { width: 20%; color: #000; background-color: #fff; margin: 2px 2px 0% 2px; border-top-left-radius: var(--border-rad); border-top-right-radius: var(--border-rad); position: relative; text-decoration: none; text-align: center; z-index: 2; /* 设置默认层级 */ } /* 给非第一个标签设置更低层级和顶部阴影 */ .tab:not(:first-child) { z-index: 1; box-shadow: 0 -3px 5px rgba(0, 0, 0, 0.2); } .tab:before, .tab:after { content: ""; position: absolute; height: 10px; width: 20px; bottom: 0; z-index: -1; /* 让伪元素在标签下方,避免遮挡前面的标签 */ } .tab:before { left: -20px; border-radius: 0 0 var(--border-rad) 0; box-shadow: var(--border-rad) 0 0 0 #fff; } .tab:after { right: -20px; border-radius: 0 0 0 var(--border-rad); box-shadow: calc(var(--border-rad) * -1) 0 0 0 #fff; } .content { background-color: #fff; height: 75vh; box-shadow: 0 10px 10px rgba(0, 0, 0, 0.3), 0 -3px 5px rgba(0, 0, 0, 0.3); border-radius: 10px; text-align: center; }
HTML代码(无需修改)
<div class="wrapper"> <div class="tabs"> <span class="tab">A</span> <span class="tab">B</span> <span class="tab">C</span> </div> <div class="content">content</div> </div>
效果说明
- 通过
z-index:2让A标签处于最高层级,B、C标签z-index:1位于下方 - B、C标签的
box-shadow:0 -3px 5px rgba(0,0,0,0.2)在顶部生成阴影,模拟被A标签遮挡的后方效果 - 伪元素设置
z-index:-1,确保标签的圆角延伸部分不会遮挡前面的标签,保持视觉连贯
内容的提问来源于stack exchange,提问作者moys
相关产品推荐
相关产品推荐

