如何在移动端导航菜单展开时隐藏banner文字?
问题描述
您好,我的banner文字始终显示,即便我点击移动端导航菜单时它也不会隐藏。


我尝试给banner文字的div设置position: relative属性,但文字仍然显示。
我的CSS代码如下:
.banner { background-image: url(../images/banner1.webp); /*imagen de fondo banner*/ background-size: cover; /*la imagen se expande a la pantalla*/ min-height: 100vh; /*altura del 100 del viewport del dispositivo*/ background-color: rgb(30, 30, 30); /*color de fondo*/ background-blend-mode: soft-light; /*propiedad de color*/ animation: banner 25s infinite linear; /*animación que llama a banner, 25seg, infinito */ } .banner .banner-text { width: 100%; height: 80px; font-weight: bold; color: white; display: flex; justify-content: center; line-height: 80px; font-size: 60px; position: absolute; top: 0; left: 0; right: 0; bottom: 0; margin: auto; overflow: hidden; }
如上所述,我尝试给banner-text添加position: relative / z-index属性,但它仍然显示在移动端菜单的上方
@media (max-width: 1024px){ .banner .banner-text{ font-size: 36px; position: relative; } }
原因分析
这是CSS层叠上下文规则导致的层级显示异常:
- 仅修改
.banner-text的定位属性没有调整层级优先级,移动端导航菜单的默认z-index低于设置过定位的.banner-text,所以文字会始终显示在菜单上层。 - 如果
.banner父元素本身设置过z-index,会生成独立层叠上下文,内部的.banner-text层级调整只会在父元素内部生效,需要同步调整.banner本身的层级。
修复方案
二选一即可:
- 给移动端导航菜单设置足够高的层级,示例代码(替换为实际的导航菜单类名):
.mobile-nav { position: fixed; z-index: 999; }
- 在移动端媒体查询中调低
.banner-text的层级:
@media (max-width: 1024px){ .banner .banner-text{ font-size: 36px; position: relative; z-index: 1; } }
如果修改后仍不生效,检查.banner元素的z-index设置,将其调整为低于导航菜单的数值即可。
内容的提问来源于stack exchange,提问作者Diego Donoso
相关产品推荐
相关产品推荐

