首頁  >  文章  >  web前端  >  詳解CSS繪製三角形箭頭圖案技術解析

詳解CSS繪製三角形箭頭圖案技術解析

高洛峰
高洛峰原創
2017-03-08 14:14:451583瀏覽

最近我想修改一下這個網站,我想在上面放置一個提示框。這是很容易,但我想讓提示框上有一個三角形的箭頭。可是,一想到這需要使用圖片,並且各種顏色,各種方向的箭頭要準備無數種,這幾乎是一種災難。幸運的是,MooTools的核心發展Darren Waddell告訴了我一個非常棒的技術:用CSS繪製三角形箭頭。使用純CSS,你只需要很少的程式碼就可以創作出各種瀏覽器都相容的三角形箭頭!

CSS程式碼

/* create an arrow that points up */
p.arrow-up {   
 width: 0;    
 height: 0;    
 border-left: 5px solid transparent;  /* left arrow slant */
 border-right: 5px solid transparent; /* right arrow slant */
 border-bottom: 5px solid #2f2f2f; /* bottom, add background color here */
 font-size: 0;   
 line-height: 0;   
}   

/* create an arrow that points down */
p.arrow-down {   
 width: 0;    
 height: 0;    
 border-left: 5px solid transparent;   
 border-right: 5px solid transparent;   
 border-top: 5px solid #2f2f2f;   
 font-size: 0;   
 line-height: 0;   
}   

/* create an arrow that points left */
p.arrow-left {   
 width: 0;    
 height: 0;    
 border-bottom: 5px solid transparent;  /* left arrow slant */
 border-top: 5px solid transparent; /* right arrow slant */
 border-right: 5px solid #2f2f2f; /* bottom, add background color here */
 font-size: 0;   
 line-height: 0;   
}   

/* create an arrow that points right */
p.arrow-rightright {   
 width: 0;    
 height: 0;    
 border-bottom: 5px solid transparent;  /* left arrow slant */
 border-top: 5px solid transparent; /* right arrow slant */
 border-left: 5px solid #2f2f2f; /* bottom, add background color here */
 font-size: 0;   
 line-height: 0;   
}

#繪製這些三角形的關鍵在於,你要讓箭頭所指方向的兩個側邊有很粗的邊框。而背向箭頭方向的一邊也是同樣粗的邊框,而這條邊的顏色就是你的三角形的顏色。邊框越粗,三角形越大。用這種方法你可以畫出各種顏色、各種大小、各種朝向的箭頭。最妙的是,你只需要幾行CSS程式碼就能達到這個效果。

使用:before和:after繪製CSS三角形

上面的CSS範例使用的是真正的頁面元素來繪製,但有時候這個真正的元素還有它用,你不能走上面直接操作,這是怎麼辦?純CSS的三角形其實還可以使用偽元素(pseudo-element)來繪製。以下就是繪製方法:

p.tooltip {   
 /* tooltip content styling in here; nothing to do with arrows */
}   

/* shared with before and after */
p.tooltip:before, p.tooltip:after {   
 content: ' ';   
 height: 0;   
 position: absolute;   
 width: 0;   
 border: 10px solid transparent; /* arrow size */
}   

/* these arrows will point up */

/* top-stacked, smaller arrow */
p.tooltip:before {   
 border-bottom-color: #fff;  /* arrow color */

 /* positioning */
 position: absolute;   
 top: -19px;   
 left: 255px;   
 z-index: 2;   
}   

/* arrow which acts as a background shadow */
p.tooltip:after {   
 border-bottom-color: #333;  /* arrow color */

 /* positioning */
 position: absolute;   
 top: -24px;   
 left: 255px;   
 z-index: 1;   
}

背向箭頭的那一邊的邊框的顏色就是三角形箭頭的顏色。畫這個箭頭並不需要同時使用:before和:after兩個偽元素-一個就夠了。而另外一個,你可以把它當作前一個的背景陰影或背景邊。

真應該早點知道這種技術!我相信在將來做介面改進時這種簡潔省事的技術將派上大用途。

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持PHP中文網。

以上是詳解CSS繪製三角形箭頭圖案技術解析的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn