這是最終實現的效果,類似於微信對話框的樣式。
分析一下這個對話框的結構,由一個小三角形和一個長方形構成。長方形很容易就可以實現,重點是如何用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>