CSS可以轻松创建各种形状,包括三角形。下面是一个使用CSS在网页上创建三角形的样例。
.triangle {
width: 0px;
height: 0px;
border-top: 50px solid red;
border-right: 50px solid transparent;
} 上述代码中,.triangle是我们要创建的CSS类名。width和height属性将元素设为零尺寸。border-top:50px solid red定义该元素上边的边框为红色,并将其宽度设置为50个像素。border-right:50px solid transparent会将右边边框的宽度设置为50px,颜色设置为透明的。这样,这个元素的形状就变成了一个等边直角三角形。
我们也可以使用伪元素before或after来实现三角形。下面是一个使用before实现三角形的例子:
.triangle2 {
width: 0px;
height: 0px;
border-left: 50px solid yellow;
border-right: 50px solid transparent;
border-bottom: 50px solid transparent;
position: relative;
}
.triangle2::before {
content: "";
position: absolute;
top: -50px;
left: 0px;
width: 0px;
height: 0px;
border-left: 50px solid transparent;
border-right: 50px solid blue;
border-bottom: 50px solid transparent;
} 上述代码中,我们使用了before伪元素。位置定位依然使用了absolute,取决于元素相对的父元素。content属性为空,使得before伪元素为空。我们还是沿用了三角形的定义方法:将元素的width,height都设为0px。border-left:50px solid yellow设置左边框为黄色,而border-right:50px solid transparent则使得右边框透明。border-bottom:50px solid transparent定义底边也透明。然后我们使用before伪元素为这个元素添加上三角形边界,即border-left:50px solid transparent定义左边透明。border-right:50px solid blue设置右边框为蓝色。border-bottom:50px solid transparent定义底边透明,而top:-50px;left:0px的定位将before伪元素定位到了triangle2元素的上方。