如何在HTML&CSS中实现滚动时图片置于菜单栏后方?
解决页面滚动时图片覆盖菜单栏的问题
我明白你现在遇到的困扰——滚动页面时轮播图片会跑到菜单栏的前方,这个其实是CSS堆叠层级(z-index)的问题,很容易修复!
问题原因
你的菜单栏使用了position: fixed固定在顶部,而轮播图容器.slidershow用了position: absolute定位。对于这类设置了定位的元素,它们的堆叠顺序默认由HTML中的出现顺序决定:后面的元素会叠加在前面的元素之上。虽然菜单是固定定位,但因为没有设置z-index属性,轮播图就会在滚动时覆盖菜单。
解决方案
只需要给.menu类添加一个足够大的z-index值,让它始终处于所有其他定位元素的上方:
.menu { background-color: rgba(0, 0, 0, 0.5); width: 100%; top: 0; position: fixed; z-index: 100; /* 新增这一行,确保菜单在最上层 */ }
补充说明
z-index仅对设置了position: relative/absolute/fixed/sticky的元素生效,你的菜单已经是fixed定位,所以这个属性会生效。- 选择
100作为z-index值是比较稳妥的,避免被其他元素的层级超过;如果之后你有需要更高层级的元素,再调整这个数值即可。
修改后的完整CSS代码
* { margin: 0; padding: 0; } body { width: 100%; height: 100%; background-color: #fff3cc; } .menu { background-color: rgba(0, 0, 0, 0.5); width: 100%; top: 0; position: fixed; z-index: 100; } .menu ul { display: inline-flex; float: right; margin: 30px; font-family: "FuturaMedium", Futura, "Century Gothic", sans-serif; } .menu ul li { list-style: none; margin: 0 20px; color: #fff; cursor: pointer; } h3 { float: left; margin-top: 30px; margin-left: 30px; font-family: "FuturaMedium", Futura, "Century Gothic", sans-serif; color: #ff8c8c; } .active { color: #a5e5ff !important; } .slidershow { width: 500px; height: 500px; overflow: hidden; } .middle { position: absolute; top: 50%; left: 25%; transform: translate(-50%, -50%); } .navigation { position: absolute; bottom: 20px; left: 50%; transform: translateX(-50%); display: flex; } .bar { width: 50px; height: 10px; border: 2px solid #fff; margin: 6px; cursor: pointer; } .bar:hover { background: #fff; } input[name="r"] { position: absolute; visibility: hidden; } .slides { width: 500%; height: 100%; display: flex; } .slide { width: 20%; transition: 0.6s; } .slide img { width: 100%; height: 100%; } #r1:checked~.s1 { margin-left: 0; } #r2:checked~.s1 { margin-left: -20%; } #r3:checked~.s1 { margin-left: -40%; } .about { margin-top: 100px; float: right; width: 50%; padding-left: 150px; margin-right: 40px; } h1 { font-family: "Lucida Grande", sans-serif; font-size: 30pt; line-height: 60px; } h2 { font-family: "Lucida Grande", sans-serif; line-height: 50px; } p { font-family: Optima, sans-serif; font-size: 13pt; line-height: 30px; } .shop-btn { margin-left: 250px; margin-top: 680px; display: inline-flex; } .shop-btn-inner { height: 50px; width: 50px; border: 2px solid transparent; border-radius: 50px; background-image: linear-gradient(#42455a, #42455a), radial-gradient(circle at top left, #fd00da, #19d7f8); background-origin: border-box; background-clip: content-box, border-box; text-align: center; } .shop-btn-inner .fa { padding: 18px 0; font-size: 13px; cursor: pointer; } .small { margin: auto 20px; cursor: pointer; font-size: 12px; color: #96ff8c; letter-spacing: 3px; }
内容的提问来源于stack exchange,提问作者KRUZ
相关产品推荐
相关产品推荐

