前端頁(yè)面開(kāi)發(fā)中經(jīng)常需要實(shí)現(xiàn)消息氣泡樣式,比如:

messagebubble3.png
實(shí)際上上述兩種效果實(shí)現(xiàn)起來(lái),并不復(fù)雜,接下來(lái)我們就來(lái)實(shí)戰(zhàn)一下。
1. 構(gòu)建消息框
消息框主體很簡(jiǎn)單,一個(gè)div,設(shè)置一下背景顏色、border-radius等即可:
.message1,.message2 {
width: 200px;
height: 80px;
margin: 100px auto;
background-color: green;
border-bottom-color:green;/*為了給after偽元素自動(dòng)繼承*/
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 代碼演示、代碼片段 - 讀你,歡迎來(lái)到讀你,http://dunizb.com/demo/
</div>
<div class="message2">
Demos 代碼演示、代碼片段 - 讀你,歡迎來(lái)到讀你,http://dunizb.com/demo/
</div>
</body>

messagebubble2.png
2 三角形箭頭
接下來(lái)我們實(shí)現(xiàn)一下圖一中第一個(gè)消息氣泡樣式,這個(gè)樣式相對(duì)簡(jiǎn)單:只需在消息框主體之前插入一個(gè)元素,然后再旋轉(zhuǎn)45度即可,在現(xiàn)有元素之前插入其他元素首選before
.message1::before {
content: '';
width: 20px;
height: 20px;
background-color: inherit;
left: -10px; /*向左側(cè)外部延伸箭頭box的一半寬度*/
position: absolute;
transform: rotate(45deg); /*旋轉(zhuǎn)45度*/
top:50%; /*箭頭在數(shù)值方向上居中*/
margin-top: -5px;
}

messagebubble4.png
3 圓弧型箭頭
圓弧型箭頭,稍微復(fù)雜些。由于涉及到弧度部分,可以考慮利用border來(lái)實(shí)現(xiàn)。首先我們通過(guò)after實(shí)現(xiàn)一個(gè)吸附在消息框右部的矩形框:
.message2::after {
content: '';
position: absolute;
width: 20px;
height: 20px;
right: -24px;
top: 0px;
background-color: red; /*為顯示需要*/
}

messagebubble5.png
前面已經(jīng)說(shuō)到,我們真正需要的是通過(guò)border來(lái)實(shí)現(xiàn)弧形效果,所以這里必然需要設(shè)置border,不過(guò)并不是所有方向都需要設(shè)置border,只需要設(shè)置底部和左部:
.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;
}

messagebubble6.png
接下來(lái)再加上右下角弧度:
.message2::after {
...
border-bottom-right-radius: 60px;
}

messagebubble7.png
此時(shí)可以看到,基本的雛形已經(jīng)出來(lái)了,接下來(lái)就是重新設(shè)置顏色了。
.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;
}

messagebubble9.png
大功告成!