You need to enable JavaScript to run this app. 如何为CSS六边形网格添加贴合边缘的渐变背景效果
优惠活动
大模型
产品
解决方案
定价
更多

如何为CSS六边形网格添加贴合边缘的渐变背景效果

实现方案

核心调整逻辑

  • 你之前把渐变加在父容器上,会被六边形的深色背景完全遮挡,自然看不到效果
  • 直接把渐变设置在.background-hexagon元素上即可,clip-path会自动将背景裁剪为六边形形状,完美贴合边缘,不会出现溢出
  • 如果需要实现左深右浅的整体渐变效果,通过:nth-child选择器给不同列的六边形设置不同透明度的渐变即可

修改后的完整代码

.background-hexagon-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    position: absolute;
    /* 移除父容器的渐变设置 */
}

.background-hexagon-row {
    margin-top: -15px;
    display: flex;
    background-color: transparent;
}

.background-hexagon {
    margin: 1px;
    width: 50px;
    height: 57.5px;
    clip-path: polygon(0% 25%,0% 75%,50% 100%,100% 75%,100% 25%,50% 0%);
    /* 双层背景实现边缘渐变效果,上层深色比下层小2px,露出的边缘即为渐变 */
    background: 
        linear-gradient(#222, #222) center/ calc(100% - 2px) calc(100% - 2px) no-repeat,
        linear-gradient(to right, #915023, transparent);
}

/* 按列设置渐变透明度,实现整体左深右浅效果,可根据实际列数调整 */
.background-hexagon-row .background-hexagon:nth-child(1) {
    background: 
        linear-gradient(#222, #222) center/ calc(100% - 2px) calc(100% - 2px) no-repeat,
        #915023;
}
.background-hexagon-row .background-hexagon:nth-child(2) {
    background: 
        linear-gradient(#222, #222) center/ calc(100% - 2px) calc(100% - 2px) no-repeat,
        #915023aa;
}
.background-hexagon-row .background-hexagon:nth-child(3) {
    background: 
        linear-gradient(#222, #222) center/ calc(100% - 2px) calc(100% - 2px) no-repeat,
        #91502366;
}
.background-hexagon-row .background-hexagon:nth-child(4) {
    background: 
        linear-gradient(#222, #222) center/ calc(100% - 2px) calc(100% - 2px) no-repeat,
        #91502322;
}

效果调整说明

  • 如果你不需要边缘渐变,要的是整个六边形填充渐变,直接删除双层背景里的linear-gradient(#222, #222) ...那一行即可,剩下的渐变会直接填充整个六边形,完全贴合边缘
  • 调整calc(100% - 2px)里的数值可以修改边缘渐变的宽度,改成4px就会有更粗的渐变边框
  • 调整各列的十六进制颜色透明度(后缀两位)可以修改渐变的过渡节奏,符合你的视觉需求

内容的提问来源于stack exchange,提问作者hbblue

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.20 02:24:04