下面為大家帶來一篇CSS3繪製六邊形的簡單實現。內容挺不錯的,現在就分享給大家,也給大家做個參考。
因為很簡單,所以先總結一下:使用CSS3繪製六邊形主要使用偽類:before和:after在源元素之前和之後再繪製兩個元素,並利用css3的邊框樣式,將這兩個元素變成三角形放置在源元素的兩端即可。
(因為之前在生物公司工作過,覺得六邊形更貼近生物分子、基因等概念,包括我們在網上搜尋關於生物分子、基因等圖片,好多也有六邊形的樣式,所以那時候在頁面做一些功能性的導航或Tag,都會覺得六邊形更貼近一些)。
完整的頁面效果如:(其實是多個六邊形定位成這樣子的。當然,也可以設定不同六邊形的顏色,這樣就可以更好的區分不同的模組功能了)。
我們可以單獨提出一個六邊形分析一下,如:
知道了分析思路,我們可以先瞭解一下如何繪製三角形,網上的列子也很多,不過沒有使用過的童鞋不用找了,下面也給出代碼和樣本,如下:
:
CSS代碼:
.arrow{ display: inline-block; width:0px; height: 0px; border-style: solid; border-width: 100px; //與padding、margin屬性類似,順序為上、右、下、左 border-color: red blue orange gray; //順序為上、右、下、左}
HTML代碼:
<p class="arrow"></p>
如所說,利用border邊框屬性,填充我們不想要的顏色為透明色,即可得到某一部分三角形,代碼和圖片效果如下。
:(左邊的三角形是我們需要的,其它的設定為了透明色)
CSS代碼:
.arrow{ display: inline-block; width:0px; height: 0px; border-bottom: 100px solid transparent; //設定透明色 border-top: 100px solid transparent; //設定透明色 border-right: 100px solid transparent; //設定透明色 border-left: 100px solid gray; }
HTML代碼:
<p class="arrow"></p>
Okay。知道了如何畫三角形,在利用CSS偽類:before和:after就可以完成我們想要繪製的六邊形了。
:before是在元素的前面插入內容
:after是在元素的後面插入內容
如果我們想要插入一些文字性的內容可以在它的 content屬性中錄入需要展示的文字,例如 content:"HELLO WORLD",不過我們的例子是不需要展示額外資訊的。我們只是需要將before和after這兩個虛擬元素變成三角形放置到固定位置即可。
給出完整的代碼如下:
<!DOCTYPE html><html><head lang="en"> <meta charset="UTF-8"> <title></title> <style type="text/css"> .sharp:before{ content:""; //不需要展現文字等內容,所以設定為空白字元 width:0px; border-bottom:80px solid transparent; border-top:80px solid transparent; border-right:40px solid #6c6; position:absolute; left:-40px; top:0px; } .sharp{ min-width:100px; height:160px; background:#6c6; display: inline-block; position: absolute; line-height: 160px; color:#FFFFFF; font-size: 20px; text-align: center; } .sharp:after{ content:""; //不需要展現文字等內容,所以設定為空白字元 width:0px; border-bottom:80px solid transparent; border-top:80px solid transparent; border-left-width:40px; border-left-style: solid; border-left-color:#6c6; position:absolute; right:-40px; top:0px; } #sharpContainer{ width:100%; height: 600px; } #sharpContainer .center{ top:200px; left:300px; } #sharpContainer .top{ top:20px; left:300px; } #sharpContainer .top-left{ top:110px; left:140px; } #sharpContainer .top-right{ top:110px; left:460px; } #sharpContainer .bottom{ top:380px; left:300px; } #sharpContainer .bottom-left{ top:290px; left:140px; } #sharpContainer .bottom-right{ top:290px; left:460px; } </style></head><body><p id="sharpContainer"> <p class="sharp center"> </p> <p class="sharp top"> </p> <p class="sharp top-left"> </p> <p class="sharp top-right"> </p> <p class="sharp bottom"> </p> <p class="sharp bottom-left"> </p> <p class="sharp bottom-right"> </p></p></body></html>
六邊形繪製其實是很簡單的效果,只要我們瞭解如何繪製三角形和使用:before,:after偽類樣式即可。以後我們在項目中就可以加入更多的不規則的圖形了
以上就是本文的全部內容,希望對大家的學習有所協助,更多相關內容請關注topic.alibabacloud.com!