这是最终实现的效果,类似于微信对话框的样式。
分析一下这个对话框的结构,由一个小三角形和一个长方形构成。长方形很容易就可以实现,重点是如何用CSS3做出一个小三角形。
一、如何生成一个三角形
总结:三角形是由设置宽度高度为0,由边框构成的正方形,分别设置边框四个边的样式,得到四个三角形拼凑在一起的效果,再设置其他方向上的边框颜色为透明色。
1、首先先做一个正方形,这个正方形不是一般的元素加上背景颜色实现的,而是对一个元素将其长和宽都设置0px,这样就相当于盒子的内容区消失。content:" ";
.box{
border:50px solid #aff;
width: 0px;height:0px;
margin:50px auto;
}
知识兔2、然后再单独设置每一条边框的样式,就可以看到出现了四个三角形拼凑在一起的效果。
.box{
border-top:100px solid #aff;
border-left:100px solid #faf;
border-right:100px solid #afa;
border-bottom:100px solid #ffa;
width: 0px;height:0px;margin:50px auto;
}
知识兔3、获得单个的三角形,取一半边框,其他边框的颜色设置为透明 transparent
这样就获得了一个三角形。
二、制作一个对话框
对话框设置圆角border-radius;文字距离边框还有一定距离所以要设置内边距 padding;文本内容垂直居中line-height;
::before伪元素在元素前面添加内容;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<style>
.main{
background-color: #6a6;
margin:50px auto;padding:16px;
width:200px;height:25px;
border-radius: 10px;line-height: 25px;
position: relative;
}
.main::before{
content:" ";
border-left: 0px solid #6a6;
border-top:10px solid transparent;
border-right:10px solid #6a6;
border-bottom:10px solid transparent;
position: absolute;left:-10px;top:18px;
}
/*::before伪元素在元素前面添加内容;*/
</style>
</head>
<body>
<div class="main">Hello World ! </div>
</body>
</html>
知识兔