两个position:fixed元素导致子元素:hover失效的原因及解决方法
问题原因与解决方案
原因很明确:当元素设置为position: fixed后,会脱离正常文档流,堆叠顺序默认由HTML中的出现顺序决定——后出现的fixed元素会覆盖先出现的。你的#boxar在HTML结构里位于nav之后,它实际上挡住了nav,导致鼠标无法触发nav div的hover事件。
解决方法是给nav设置更高的z-index值,让它在堆叠层级上优先于#boxar:
修复后的CSS代码
nav { border: 5px solid rgb(255, 0, 0); width: 96.5vw; position: fixed; display: flex; top: 0; left: 0; height: 10vh; background-color: rgb(255, 216, 143); justify-content: space-evenly; z-index: 10; /* 添加此行提升堆叠层级 */ } nav div { position: relative; bottom: 1vh; flex-grow: 0.1; } nav div:hover { background-color: red; } #boxar { border: 10px solid rgb(156, 125, 0); position: fixed; top: 0; left: 0; width: 95vw; height: 97vh; }
设置后nav会位于#boxar上层,鼠标就能正常触发子元素的hover效果。
内容的提问来源于stack exchange,提问作者Golden Orange
相关产品推荐
相关产品推荐

