- 在做项目的过程中,遇到了要写一个气泡的样式,先布局了矩形部分,但小三角形的旗气泡遇到一点困难。后来梳理了一下,以此记录。
- 首先是三角形的画法:三角形的原理就是矩形,然后分成四个三角形,一般使用border来画一个三角形,如下图所示,我们给一个形状设置border属性时,一般是一下这种样式,如果我们不要里面的矩形,也就是里面的部分width和height都设置为0,那么只剩下border的宽度,形成图2这种形式
图2:
- 四个border可以形成一个矩形,然后就可以根据设置不同的border画出我们想要的三角形了。通过给三角形设置不同的位置,就可以画出我们想要的气泡,画一个具体的气泡形式的代码如下:
<!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>css画三角形</title>
<style type="text/css">
.popover{
position: relative;
width: 100%;
height: 800px;
}
.div{
position: absolute;
left: 30px;
top: 30px;
width: 200px;
height: 100px;
background-color: white;
border: 1px solid rgb(240,240,240);
box-shadow: 0px 0px 5px 5px rgb(235, 235, 235);
/*-5px -5px 5px rgb(230, 230, 230);*/
border-radius: 5px;
box-sizing: border-box;
}
.triangle-left{
position: absolute;
top: 40px;
left: -19px;
width: 0;
height: 0;
border-top: 10px solid transparent;
border-bottom: 10px solid transparent;
border-left: 10px solid transparent;
border-right: 10px solid white;
}
.triangle-right{
position: absolute;
top: 40px;
right: -19px;
width: 0;
height: 0;
border-top: 10px solid transparent;
border-bottom: 10px solid transparent;
border-left: 10px solid white;
border-right: 10px solid transparent;
}
.triangle-bottom{
position: absolute;
top: 100%;
left: calc(50% - 19px);
width: 0;
height: 0;
border-top: 10px solid white;
border-bottom: 10px solid transparent;
border-left: 10px solid transparent;
border-right: 10px solid transparent;
}
.triangle-top{
position: absolute;
top: 100%;
left: calc(50% - 19px);
width: 0;
height: 0;
border-top: 10px solid transparent;
border-bottom: 10px solid white;
border-left: 10px solid transparent;
border-right: 10px solid transparent;
}
</style>
</head>
<body>
<div class="popover">
<!-- <div class="div">
三角形朝左
<div class="triangle-left"></div>
</div>
<div class="div">
三角形朝右
<div class="triangle-right"></div>
</div>
<div class="div">
三角形朝上
<div class="triangle-top"></div>
</div> -->
<div class="div">
三角形朝下
<div class="triangle-bottom"></div>
</div>
</div>
</body>
</html>
气泡朝下的形式如图所示: