当前位置:首页 > CSS

css3制作六边体

2026-02-27 02:36:36CSS

使用CSS3制作六边体

六边体(六边形)可以通过CSS3的clip-path属性或transform属性结合伪元素实现。以下是两种常见方法:

方法一:使用clip-path属性

clip-path通过多边形裁剪直接生成六边形形状,代码简洁且易于调整。

.hexagon {
  width: 100px;
  height: 100px;
  background-color: #3498db;
  clip-path: polygon(
    50% 0%, 
    100% 25%, 
    100% 75%, 
    50% 100%, 
    0% 75%, 
    0% 25%
  );
}

参数说明

  • polygon定义六边形的6个顶点坐标,按顺时针或逆时针顺序排列。
  • 百分比值基于元素的宽高,50% 0%表示顶部中点。

方法二:使用伪元素与旋转

通过旋转两个矩形叠加形成六边形,兼容性较好但代码稍复杂。

.hexagon {
  width: 100px;
  height: 55px;
  background-color: #3498db;
  position: relative;
}

.hexagon::before,
.hexagon::after {
  content: "";
  position: absolute;
  width: 100%;
  height: 100%;
  background-color: inherit;
}

.hexagon::before {
  transform: rotate(60deg);
}

.hexagon::after {
  transform: rotate(-60deg);
}

关键点

  • 主元素高度为宽度的约55%(height: 55px对应width: 100px)。
  • 伪元素通过60°旋转形成六边形的两侧。

添加3D效果

若需立体六边体,可结合transform-style和透视:

.hexagon-3d {
  width: 100px;
  height: 100px;
  position: relative;
  transform-style: preserve-3d;
  transform: rotateX(20deg) rotateY(30deg);
}

.hexagon-3d .face {
  position: absolute;
  width: 100%;
  height: 100%;
  background-color: rgba(52, 152, 219, 0.8);
  clip-path: polygon(50% 0%, 100% 25%, 100% 75%, 50% 100%, 0% 75%, 0% 25%);
}

.hexagon-3d .front {
  transform: translateZ(50px);
}

.hexagon-3d .back {
  transform: translateZ(-50px) rotateY(180deg);
}

结构示例

<div class="hexagon-3d">
  <div class="face front"></div>
  <div class="face back"></div>
</div>

注意事项

  • clip-path的兼容性需注意,旧版浏览器可能需要-webkit-前缀。
  • 3D效果依赖transform-style: preserve-3d,父容器需设置透视(如perspective: 500px)。

css3制作六边体

标签: 六边体
分享给朋友: