gogogo
管理员
管理员
  • UID25
  • 粉丝0
  • 关注0
  • 发帖数1377
阅读:6020回复:1

CSS 消息气泡实现

楼主#
更多 发布于:2019-03-29 16:09
前端页面开发中经常需要实现消息气泡样式,比如:






实际上上述两种效果实现起来,并不复杂,接下来我们就来实战一下。


1. 构建消息框
消息框主体很简单,一个div,设置一下背景颜色、border-radius等即可:


.message1,.message2 {
  width: 200px;
  height: 80px;
  margin: 100px auto;
  background-color: green;
  border-bottom-color:green;/*为了给after伪元素自动继承*/
  color: #fff;
  font-size: 12px;
  font-family: Arial;
  line-height: 18px;
  padding: 5px 12px 5px 12px;
  box-sizing: border-box;
  border-radius: 6px;
  position: relative;
  word-break: break-all;
}


<body>
  <div class="message1">
    Demos 代码演示、代码片段 - 读你,欢迎来到读你,http://dunizb.com/demo/
  </div>


  <div class="message2">
    Demos 代码演示、代码片段 - 读你,欢迎来到读你,http://dunizb.com/demo/
  </div>






2 三角形箭头
接下来我们实现一下图一中第一个消息气泡样式,这个样式相对简单:只需在消息框主体之前插入一个元素,然后再旋转45度即可,在现有元素之前插入其他元素首选before


.message1::before {
  content: '';
  width: 20px;
  height: 20px;
  background-color: inherit;
  left: -10px; /*向左侧外部延伸箭头box的一半宽度*/
  position: absolute;
  transform: rotate(45deg); /*旋转45度*/
  top:50%; /*箭头在数值方向上居中*/
  margin-top: -5px;
}
1
2
3
4
5
6
7
8
9
10
11




3 圆弧型箭头
圆弧型箭头,稍微复杂些。由于涉及到弧度部分,可以考虑利用border来实现。首先我们通过after实现一个吸附在消息框右部的矩形框:


.message2::after {
  content: '';
  position: absolute;
  width: 20px;
  height: 20px;
  right: -24px;
  top: 0px;
  background-color: red; /*为显示需要*/
}






前面已经说到,我们真正需要的是通过border来实现弧形效果,所以这里必然需要设置border,不过并不是所有方向都需要设置border,只需要设置底部和左部:


.message2::after {
    content: '';
    position: absolute;
    width: 20px;
    height: 20px;
    right: -24px;
    top: 0px;
    background-color: red;
    border-width: 0 0 20px 20px;
    border-style: solid;
    border-left-color: blue;
    border-bottom-color: yellow;
}
1
2
3
4
5
6
7
8
9
10
11
12
13




接下来再加上右下角弧度:


.message2::after {
  ...
  border-bottom-right-radius: 60px;
}
1
2
3
4




此时可以看到,基本的雏形已经出来了,接下来就是重新设置颜色了。


.message2::after {
  content: '';
  position: absolute;
  width: 20px;
  height: 20px;
  right: -24px;
  top: 0px;
  border-width: 0 0 20px 20px;
  border-style: solid;
  border-left-color: transparent;
  border-bottom-color:inherit;
  border-bottom-right-radius: 60px;
}
1
2
3
4
5
6
7
8
9
10
11
12
13




大功告成!
gogogo
管理员
管理员
  • UID25
  • 粉丝0
  • 关注0
  • 发帖数1377
沙发#
发布于:2019-03-29 16:10
游客


返回顶部