在CSS中使用伪元素:before和:after,可以实现很多有趣的效果,比如写一个五角星。
.star {
position: relative;
display: inline-block;
width: 0;
height: 0;
border-style: solid;
border-width: 0 20px 30px 20px;
border-color: transparent transparent #ffc107 transparent;
transform: rotate(35deg);
margin-right: 10px;
}
.star:before {
content: "";
position: absolute;
top: -12px;
left: -20px;
display: inline-block;
width: 0;
height: 0;
border-style: solid;
border-width: 0 20px 30px 20px;
border-color: transparent transparent #ffc107 transparent;
transform: rotate(-70deg);
}
.star:after {
content: "";
position: absolute;
top: -12px;
left: 20px;
display: inline-block;
width: 0;
height: 0;
border-style: solid;
border-width: 0 20px 30px 20px;
border-color: transparent transparent #ffc107 transparent;
transform: rotate(70deg);
} 以上代码中,我们先定义了一个.star类来设置五角星的基本样式,其中用到了border属性来实现正五边形。然后利用:before和:after伪元素来添加另外两个三角形,完成五角星的绘制。
通过调整:before和:after伪元素的位置和角度,可以实现不同形状和旋转角度的星星。而且,这种方法可以应用于其他图形的绘制。