前端开发经常会遇到三角形的装饰,今天我们来用css实现。还是一样先上全代码,在逐步解析。
全代码展示
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<style>
.title {
position: relative;
padding-left: 16px;
}
.title::before {
content: "";
position: absolute;
border-width: 8px;
border-style: solid;
border-color: transparent transparent transparent red;
top: 50%;
left: 0;
margin-top: -8px;
}
</style>
<body>
<div class="title">css实现三角形</div>
</body>
</html>
效果展示
代码解析
1.用div写一个标题
<div class="title">css实现三角形</div>
2.标题样式。
设置相对定位,并设置内边距,给三角形留下空间
.title {
position: relative;
padding-left: 16px;
}
3.三角形样式
这里用到了 ::before 伪类元素,简单解释下,他会在元素(本代码中为“title”)内容前插入新的内容(本代码content中的内容为空)。
重点:不设置元素的宽高,只设置4边的宽度和颜色结果如下图
// 4边都设置颜色
.title::before {
content: "";
position: absolute;
border-width: 8px;
border-style: solid;
border-color: blue green yellow red;
top: 50%;
left: 0;
margin-top: -8px;
}
通过让其他3边颜色透明就能实现三角形效果,给需要显示的三角形的边线设置颜色。
(tip:三角形的总高是上下边线宽度之和,所以偏移一半高度居中)
// 只给左边设置颜色,其余三边线设置透明
.title::before {
content: "";
position: absolute;
border-width: 8px;
border-style: solid;
border-color: transparent transparent transparent red;
top: 50%;
left: 0;
margin-top: -8px;
}