CSS画图形在Web运用中时常看到,比如三角形、五角星,心形,Ribbon等。不过以前使用CSS绘制图形一般都是借助于border来绘制,但这样的方式受到一定的限制,而且实用价值也有所限制。这篇文章将介绍使用CSS的clip-path来完成正多边形的绘制,并且借助CSS预处理器Sass给这两种方法定义对应的混合宏和函数,实现正多边形的开发。
border和多个元素绘制多边形
使用border和多个HTML元素绘制三角形,Ribbon等对于我们来说还是易事,也是常见的事,并且实用性、可扩展性并不受到太多限制。但对于一个多边形来说,那就相对而言会麻烦很多了。比如一个正六边形。比如下面的一个示例:
.hexagon {
width: 100px;
height: 55px;
background: red;
margin: 150px auto;
position: relative;
&:before,
&:after {
content: "";
position: absolute;
width: 0;
height: 0;
}
&:before {
top: -25px;
left: 0;
border-left: 50px solid transparent;
border-right: 50px solid transparent;
border-bottom: 25px solid red;
}
&:after {
bottom: -25px;
left: 0;
border-left: 50px solid transparent;
border-right: 50px solid transparent;
border-top: 25px solid red;
}
}
将这个示例扩展一下,采用SCSS来写,原理还是使用border和多个HTML元素配合:
$PI: 3.141592653589793;
@mixin border-polygon($num, $color: #000, $radius: 64px) {
position: relative;
height: 2.5*$radius;
width: 2.5*$radius;
div {
$halfWidth: tan($PI / $num) * $radius + 1; /* + 1.5 to account for anti-aliasing */
border-top: #{$radius} solid $color;
border-left: #{$halfWidth} solid transparent;
border-right: #{$halfWidth} solid transparent;
position: absolute;
left: 50%;
top: 50%;
transform-origin: 50% 100%;
@for $i from 0 through $num {
&:nth-child(#{$i}) {
transform: translate(-50%, -100%) rotate(360deg / $num * $i);
}
}
}
}
调用定义好的mixin:border-polygon:
$maxNum: 10;
@for $i from 1 through $maxNum {
$num: $i + 3;
.polygon:nth-of-type(#{$i})::after {
content: "#{$num}";
}
.borders .polygon:nth-of-type(#{$i}) {
@include border-polygon($num, #c00);
}
}
添加一些额外的CSS,看到的效果如下: