css3制作六边体
CSS3 制作六边体
使用 CSS3 可以创建六边形(六边体),主要通过 clip-path 或 transform 属性实现。以下是两种常见方法:
使用 clip-path 属性
clip-path 通过裁剪区域定义六边形形状。代码示例如下:
<div class="hexagon"></div>
.hexagon {
width: 100px;
height: 100px;
background-color: #3498db;
clip-path: polygon(
50% 0%,
100% 25%,
100% 75%,
50% 100%,
0% 75%,
0% 25%
);
}
clip-path: polygon()定义六边形的顶点坐标,按顺时针顺序排列。- 调整
width和height可改变六边形大小,background-color修改颜色。
使用 transform 和伪元素
通过旋转两个矩形叠加形成六边形:
<div class="hexagon-transform"></div>
.hexagon-transform {
position: relative;
width: 100px;
height: 55px;
background-color: #e74c3c;
margin: 25px 0;
}
.hexagon-transform::before,
.hexagon-transform::after {
content: "";
position: absolute;
width: 100%;
height: 100%;
background-color: inherit;
}
.hexagon-transform::before {
transform: rotate(60deg);
}
.hexagon-transform::after {
transform: rotate(-60deg);
}
- 主体部分为矩形,伪元素通过旋转 60° 和 -60° 补全六边形。
height需为width的约 55% 以保持正六边形比例。
添加动画效果
为六边形添加悬停旋转动画:
.hexagon {
transition: transform 0.5s ease;
}
.hexagon:hover {
transform: rotate(30deg);
}
浏览器兼容性
clip-path在现代浏览器中支持良好,但旧版需前缀(如-webkit-clip-path)。transform方法兼容性更广,适合需要支持老版本浏览器的场景。
通过以上方法可灵活创建六边形,并扩展为按钮、图标或网格布局元素。

