如何将SVG或图片置于六边形边框后方
解决六边形内图片覆盖边框的问题
核心问题分析
当前图片直接绝对定位在.hexagon容器下,未被.topContainer的裁剪路径限制,导致超出边框的部分无法隐藏;同时.hexagon:before的层级未正确设置,使得边框被图片覆盖。
修复方案
- 将图片移入
.topContainer内部,利用其clip-path自动裁剪超出容器的部分 - 给
.hexagon:before设置z-index: 1,确保边框层级高于内部内容 - 调整图片定位参数,使其适配容器内部边距
修改后的代码
CSS部分
.App { background: black; min-height: 100vh; width: 100%; overflow: hidden; } .gridComponent { margin-top: 35px; display: grid; justify-content: center; gap: 2rem; } .hexagon { position: relative; height: 600px; width: 339px; background: rgb(89, 90, 145); } .hexagon:before { position: absolute; content: ""; top: 10px; left: 10px; height: calc(100% - 20px); width: calc(100% - 20px); background: #1e40af; z-index: 1; /* 确保边框层级高于内部内容 */ } .hexagon, .hexagon:before { -webkit-clip-path: polygon(50% 0, 100% 10%, 100% 90%, 50% 100%, 0 90%, 0 10%); clip-path: polygon(50% 0, 100% 10%, 100% 90%, 50% 100%, 0 90%, 0 10%); } .topContainer { position: relative; width: 339px; height: 300px; z-index: 0; /* 内部内容层级低于边框 */ } .topContainer:before { position: absolute; content: ""; top: 10px; left: 10px; height: calc(100% - 20px); width: calc(100% - 20px); background: green; } .topContainer, .topContainer:before { -webkit-clip-path: polygon(50% 0, 100% 20%, 100% 100%, 50% 100%, 0 100%, 0 20%); clip-path: polygon(50% 0, 100% 20%, 100% 100%, 50% 100%, 0 100%, 0 20%); } .logoVitality { position: absolute; width: 212.06px; height: 257.19px; top: 10px; /* 适配内部边距 */ left: 10px; /* 调整定位方向,更直观控制位置 */ } .divider { position: absolute; width: 339px; height: 10px; top: 289.5px; background: black; z-index: 1; /* 分隔线层级高于内部内容 */ } .bottomContainer { position: relative; width: 339px; height: 300px; z-index: 0; } .bottomContainer:before { position: absolute; content: ""; top: 0px; left: 10px; height: calc(100% - 10px); width: calc(100% - 20px); background: grey; } .bottomContainer, .bottomContainer:before { -webkit-clip-path: polygon(50% 100%, 100% 81%, 100% 0, 50% 0, 0 0, 0 81%); clip-path: polygon(50% 100%, 100% 81%, 100% 0, 50% 0, 0 0, 0 81%); }
HTML部分
<div class="App"> <div class="gridComponent"> <div class="hexagon"> <div class="topContainer"> <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/b/b0/NewTux.svg/640px-NewTux.svg.png" class="logoVitality"/> </div> <div class="divider"></div> <div class="bottomContainer"></div> </div> </div> </div>
关键修改说明
- 图片移入
.topContainer后,容器的clip-path会自动裁剪超出部分,无需额外设置overflow:hidden z-index的设置确保边框和分隔线始终显示在内容上方- 调整图片的
top和left值,使其适配容器内部的边距,避免被边框遮挡
内容的提问来源于stack exchange,提问作者Burnir
相关产品推荐
相关产品推荐

