html用css画多边形,Sass绘制多边形_Preprocessor, Sass, SCSS, clip-path, CSS处理器, 会员专栏 教程_W3cplus...

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,看到的效果如下:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值