头部元素使用clip-path时图片z-index失效无法置于顶层问题求助
问题核心原因
- 父元素设置
clip-path后,所有内部子元素都会被该裁剪路径约束,超出路径范围的部分会被直接裁剪,和子元素的z-index取值无关 - 代码中设置的
z-index全部未生效:z-index仅对position属性不为static的元素生效,你没有给对应元素添加任何定位属性
解决方案
最优改动方案是将裁剪逻辑移到header的伪元素上,header本身不设置clip-path,这样内部子元素不会被裁剪,具体修改后的CSS如下:
.header { position: relative; /* 提供定位上下文 */ height: 95vh; z-index: 1; /* 移除原来的负z-index,避免被页面其他元素遮挡 */ /* 背景和clip-path逻辑移到伪元素 */ &::before { content: ''; position: absolute; top: 0; left: 0; width: 100%; height: 100%; background: linear-gradient(to right bottom, rgba($color-black, .85), rgba($color-black, .85)), url(../img/background.jpg); background-size: cover; background-position: center; clip-path: polygon(0 0, 100% 0, 100% 15%, 60% 100%, 0 100%); z-index: -1; /* 伪元素放在最底层作为背景 */ } &__navigation { background-color: $color-secondary; } &__flex { display: flex; align-items: flex-end; } &__textbox { flex: 0 0 50%; padding: 20vh 5vw 0 0; &--text { font-size: 1.6rem; margin-bottom: 4rem; color: $color-light; } } &__photo { flex: 1; position: relative; /* 添加定位让z-index生效 */ z-index: 10; &--img { display: block; } } }
逻辑说明
将需要裁剪的背景单独放在绝对定位的伪元素中,header本身不做裁剪,内部的统计图片即使超出原clip-path的范围也不会被剪掉,伪元素的z-index设为-1,会在header内部所有内容的下方,不影响导航、文字等内容的正常显示。
内容的提问来源于stack exchange,提问作者hussain shah
相关产品推荐
相关产品推荐

