一、目標
目標完成下圖效果:
二、完成
1、分析
在::before和::after偽元素的用法一文中有說到使用::befrore和::after可以完成一個六邊形。這個案例是用一個#star-six完成一個正三角形,通過::after實現一個倒三角形,然后絕對定位放好位置。我們接下來也用這個思路完成。
2、完成
第一步,先完成如下基本的效果,實現一個在瀏覽器中居中的文本
代碼如下:
<style> .middle{ text-align:center; } .title{ background-color:black; color:#f3e14f; display:inline-block; font-size:18px; height:40px; line-height:40px; padding:0 50px; } </style> <div class="middle"> <h5 class="title">升級有好禮</h5> </div>
第二步,做左右兩邊尖尖的效果。可以根據做五角星的代碼修改。
代碼如下:
<style> #star-three { width: 0; height: 0; border-left: 100px solid transparent; border-top: 50px solid red; border-bottom: 50px solid red; /* position: relative;*/ } </style> <div id="star-three"></div>
第三步,通過::before來實現第二步中的效果。
代碼還是第二步中的代碼,但是是通過::before來實現記得寫上content:""。然后調整一下尺寸。
.title::before{ width: 0; height: 0; border-left: 40px solid transparent; border-top: 20px solid red; border-bottom: 20px solid red; content: ""; }
如果給border-left設置藍色會發現效果如下。【原理還不是很懂,不知道這個高度是因為什么原因??】
結果這是什么鬼?不是想要的效果。此時需要調整布局。
第四步,使用絕對定位調整布局。
.title設置relative,.title::before設置absolute。效果如下。
第五步,通過left調整。
.title{ background-color:black; color:#f3e14f; display:inline-block; font-size:18px; height:40px; line-height:40px; position:relative; padding:0 50px; } .title::before{ width: 0; height: 0; border-left: 40px solid transparent; border-top: 20px solid red; border-bottom: 20px solid red; content: ""; position:absolute; left:-40px; }
第六步,同理,通過::after實現右邊效果。
.title::after{ width: 0; height: 0; border-right: 40px solid transparent; border-top: 20px solid red; border-bottom: 20px solid red; content: ""; position:absolute; right:-40px; }
第七步,改下顏色就好了。
完整代碼如下:

<!DOCTYPE html> <html> <head> <meta charset="utf-8"/> <title>demo of starof</title> <style> .middle{ text-align:center; } .title{ background-color:black; color:#f3e14f; display:inline-block; font-size:18px; height:40px; line-height:40px; position:relative; padding:0 50px; } .title::before{ width: 0; height: 0; border-left: 40px solid transparent; border-top: 20px solid black; border-bottom: 20px solid black; content: ""; position:absolute; left:-40px; } .title::after{ width: 0; height: 0; border-right: 40px solid transparent; border-top: 20px solid black; border-bottom: 20px solid black; content: ""; position:absolute; right:-40px; } </style> </head> <body> <div class="middle"> <h5 class="title">升級有好禮</h5> </div> </body> </html>
效果
3、瀏覽器兼容性
IE8如果要使用before和after偽元素,加上<!DOCTYPE html>,然后使用單冒號的:before和:after。
IE6,IE7是不支持的。
IE6和IE7兼容性的處理可參考:小tip:我是如何在實際項目中使用before/after偽元素的
本文作者starof,因知識本身在變化,作者也在不斷學習成長,文章內容也不定時更新,為避免誤導讀者,方便追根溯源,請諸位轉載注明出處:http://www.cnblogs.com/starof/p/4832598.html有問題歡迎與我討論,共同進步。