突然被人问到:css怎么实现一个六边形?有点懵,今天一起来总结下:
本文提供二种实现思路:
1、将六边形拆分为一个矩形+二个三角形,利用伪元素after和before来实现;
2、利用overflow:hidden + css3中的transform:rotate旋转不同角度来实现;
具体实现代码如下:
<!--第一种方案:矩形+左右两个三角形来实现--> <div class="one"></div> <style> .one{ width: 120px; height: 208px; background-color: aqua; position: relative; margin: 0 100px; } .one:before{ content: ""; width: 0; height: 0; position: absolute; top: 0; left: -60px; border-top: 104px solid transparent; border-bottom: 104px solid transparent; border-right: 60px #0f0 solid; border-left:none; } .one:after{ content: ""; width: 0; height: 0; position: absolute; top: 0; left: 120px; border-top: 104px solid transparent; border-bottom: 104px solid transparent; border-right: none; border-left:60px #0f0 solid; } </style>
<!--第二种方案:rotate + overflow:hidden来实现--> <div class="first"> <div class="two"> <div class="three"> </div> </div> </div> <style> .first{ width: 200px; height: 250px; overflow: hidden; transform: rotate(120deg); } .two{ width: 100%; height: 100%; overflow: hidden; transform: rotate(-60deg); } .three{ width: 100%; height: 100%; overflow: hidden; transform: rotate(-60deg); background: red; } </style>