利用CSS的Border属性来创造三角形

guu同学昨日问起是否有实现斜线的CSS样式,当时答曰没有——或者说,IE上没有,支持绘图的Canvas元素是HTML5的东西,还没有在IE中得到支持。
今天突然想起这个问题想到可以利用border形成的那条中间线来模拟这种效果,虽称不上完美,但也似乎是个可以变通的方法。当然,局限性也很大,比如不可能自由旋转,边必须是上下左右的某个固定的方向,不能在div里面放文字。

那么效果可以点击这里

代码(其实已经全部包括在上面的HTML文件中了):

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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<title>Triangle Demo</title>
	<style>
	body{
		margin:0;
		padding:10px 30px;
	}
	.text{
		clear:both;
		font-size:12px;
		line-height:30px;
	}
	.triangle{
		background:#fff;
		width:0px;
		height:0px;
		overflow:hidden;
		float:left;
		margin-left:10px;
	}
	#triangle1{
		border-top:100px solid #fff;
		border-left:200px solid #03f;
		border-bottom:100px solid #fff;
	}
	#triangle2{
		border-top:100px solid #fff;
		border-right:200px solid #06f;
		border-bottom:100px solid #fff;
	}
	#triangle3{
		border-top:200px solid #09f;
		border-left:100px solid #fff;
		border-right:100px solid #fff;
	}
	#triangle4{
		border-bottom:200px solid #0cf;
		border-left:100px solid #fff;
		border-right:100px solid #fff;
	}
	#triangle5{
		border-top:100px solid #c00;
		border-left:100px solid #fff;
		border-bottom:100px solid #0c0;
		border-right:100px solid #fff;
	}
	#triangle6{
		border-top:150px solid #c00;
		border-left:150px solid #0c0;
		border-bottom:50px solid #fff;
		border-right:50px solid #fff;
	}
	#triangle7{
		border-top:100px solid #fff;
		border-left:100px solid #c00;
		border-bottom:100px solid #0c0;
		border-right:100px solid #00c;
	}
</style>
</head>
 
<body>
	<div class="text">
		基本形状:
	</div>
	<div id="triangle1" class="triangle"></div>
	<div id="triangle2" class="triangle"></div>
	<div id="triangle3" class="triangle"></div>
	<div id="triangle4" class="triangle"></div>
 
	<div class="text">
		复合形状(为了区分不同的边,用了不同的颜色):
	</div>
	<div id="triangle5" class="triangle"></div>
	<div id="triangle6" class="triangle"></div>
	<div id="triangle7" class="triangle"></div>
 
	<div class="text">
		<p>
		通过border的其它组合还可以拼出更多的形状(七巧板->四巧板?)……嗯,看来可以考虑写个javascript专门绘制三角形了
		</p>
	</div>
</body>
</html>

No Responses

Leave a Comment

(Necessary)

(Necessary, will not be published)

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.