通常,我们做上图那个三角形,一般都是做张图,而且需要两张,因为一般都是下拉菜单的效果,需要有个hover的样式,箭头是反的。那是不是有更好的办法呢,毕竟要用两张图片来解决这么一个小问题太浪费资源了,于是,下面我要用纯CSS的方法来解决这一问题,用到的只需css的一个属性,就是border-width
我们先来看个样式,如果设置元素边框,会怎么样:
test
似乎看不出什么,让我给四个边框加上不同的颜色吧再看看吧:
test
是不是发现了些什么?对,让我们把中间的文字去掉吧:
这样,就出现4个三角形了,然后我们如果需要顶部那个三角形,只需要将border的left、right、bottom设置成背景色就行了:
这样,我们需要的三角形就出现了,并且可以设置4个不同方向的了:
样式代码很简单,就几句话:
1
2
3
4
5
6
|
float
:
left
;
border
-
style
:
solid
;
border
-
width
:
10px
;
border
-
color
:
#000 #ccc #ccc #ccc;
height
:
0
;
width
:
0
;
font
-
size
:
0
;
|
实际应用
比如我们要使用向下的箭头(兼容IE6写法)
HTML代码:
1
|
<
div
class
=
"demo"
>
<
span
class
=
"bottom-arrow"
>
<
/
span
>
<
/
div
>
|
CSS代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
.
demo
{
position
:
relative
}
.
bottom
-
arrow
{
position
:
absolute
;
top
:
10px
;
left
:
0px
;
border
-
style
:
solid
;
border
-
width
:
100px
;
border
-
color
:
#000000 transparent transparent transparent;/*上边框设置想要的颜色*/
height
:
0
;
width
:
0
;
font
-
size
:
0
;
_border
-
color
:
#000000 tomato tomato tomato ; /*边框透明色 For IE6-*/
_filter
:
chroma
(
color
=
tomato
)
;
/*边框透明色 For IE6-*/
}
|
说明:
这里的演示是用了边框透明色,如果你用不到透明的话,直接设置border-color为你需要的颜色就可以了,免去为了兼容IE6的透明边框滤镜写法
Chroma属性可以设置一个对象中指定的颜色为透明色,它的表达式如下:
Filter:Chroma(color=color)
这个属性的表达式是不是很简单,它只有一个参数。只需把您想要指定透明的颜色用Color参数设置出来就可以了。