用CSS即可绘制出各种箭头,无需裁剪图片,甚至没有用到CSS3的东西。对浏览器支持良好。
原理非常简单,通过截取border(边框)的部分“拐角”实现,几行CSS代码即可理解:
当元素宽、高和边框的宽相近(等)时,改变某一边的颜色可以看到一个梯形;
1 2 3 4 5 6 7 8 9 10 | <div id="demo11"></div><style>#demo11 { border: 10px solid #000; border-left-color: #f00; width: 10px; height: 10px;}</style> |
当元素宽、高为零,且其他边为透明颜色时,可以形一个三角形。
1 2 3 4 5 6 7 8 9 10 | <div id="demo12"></div><style>#demo12 { border: 10px solid #000; border-left-color: #f00; width: 0; height: 0;}</style> |
改变各个边的宽度,即通过调整“边框”厚度可以配置出任意角度
1 2 3 4 5 6 7 8 9 10 | <div id="demo14"></div><style>#demo14 { border: 10px solid transparent; border-left: 20px solid #f00; width: 0; height: 0px;}</style> |
三角形可以通过伪元素绘制出,而无需改变原来的DOM结构
文字内容1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | <span id="demo15">文字内容</span><style>#demo15{ position: relative;}#demo15:after { border: 10px solid transparent; border-left: 10px solid #f00; width: 0; height: 0; position: absolute; content: ' '}</style> |
通过伪元素绘制出的两个,一个与背景色相同覆盖部分红色箭头,形成三角线
文字内容1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | <span id="demo15">文字内容</span><style>#demo16{ position: relative;}#demo16:after, #demo16:before { border: 10px solid transparent; border-left: 10px solid #fff; width: 0; height: 0; position: absolute; top: 0; right: -20px; content: ' '}#demo16:before { border-left-color: #f00; right: -21px;}</style> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | <ul id="demo17"> <li>文字内容 Tab1</li> <li>文字内容 Tab2</li> <li>文字内容 Tab3</li></ul><style>#demo17{ font-size: 10px; height: 24px;}#demo17 li { float: left; position: relative; list-style: none; margin: 0 20px 12px -19px; border-top: solid 1px #ddd; border-bottom: solid 1px #ddd; padding-left: 12px;}#demo17 li:after, #demo17 li:before { border: 10px solid transparent; border-left: 10px solid #fff; width: 0; height: 0; position: absolute; top: 0; right: -18px; content: ' '}#demo17 li:before { border-left-color: #ddd; right: -19px;}</style> |
这里还有另一种效果,使用三角形跟矩形组合成提示框,代码来自这篇文章: Css arrows and shapes without markup
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | <div id="demo"></div><style>#demo { width: 100px; height: 100px; background-color: #ccc; position: relative; border: 4px solid #333;}#demo:after, #demo:before { border: solid transparent; content: ' '; height: 0; left: 100%; position: absolute; width: 0;}#demo:after { border-width: 9px; border-left-color: #ccc; top: 15px;}#demo:before { border-width: 14px; border-left-color: #333; top: 10px;}</style> |
本文作者:newghost
原文地址:http://ourjs.com/detail/532bc9f36922aa7e1d000001