css绘制三角形

css实现三角形的原理是:当元素的宽高为0,边框(border)不为0时,四个角边框交界重叠处分45度角平分。

{
width: 0;
height: 0;
border-top: 40px solid #000;
border-right: 40px solid #ff0000;
border-left: 40px solid #ff0000;
border-bottom: 40px solid #000;
}
效果如下:

所以,如果我们要做倒立三角形、向右的、或者向左的三角形等,可以设三个边的边框,其中两个透明。比如:
{
width: 0;
height: 0;
border-top: 40px solid transparent;
border-left: 40px solid #ff0000;
border-bottom: 40px solid transparent;
}
效果如下:


可是,当我们想做一种类似于下图这样的小三角时:


该如何去做呢,其实道理是一样的,只不过是用了两个这样的三角,重叠起来,另一个boder的颜色设为透明或白色,稍微做一点偏移
把这个三角挡住,留出你想要的宽度即可。还有,实现三角的方法,我用了两种,一个是伪类,一个是大盒子包含了两个小盒子,下面是代码:
<!DOCTYPE html>

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>CSS三角的写法</title>
<style type="text/css">
body{
background-color:#fff;
}
span{
margin:100px;
position:relative;
}
em,b{
border-width:10px;
border-style:dashed dashed solid dashed ; /*注意只有左边框为实线,其他为虚线 为了照顾ie*/
border-color: transparent transparent blue transparent ; /*只有左边框有颜色,其他为透明*/
width:0; height:0;
font-size:0; /*照顾ie6不能定义小于19像素盒子高度的问题。*/
position:absolute;
top:0; left:0;
}
b{ top:1px; border-bottom-color:#fff;} /*此时,如果给b 左移动5像素 就会得到如下图:*/
#content:before, #content:after{
position:absolute;
border-left:9px solid transparent;
border-right:9px solid transparent;
border-bottom:9px solid red;
content:" ";
display:block;
width:0;
height:0
}
#content:after{
top: 27px;
border-bottom-color: #fff;
}
</style>
</head>
<body>
<span> <!--大盒子 里面包含两个小盒子-->
<em></em>
<b></b>
</span>
<div id="content"></div>
</body>
</html>

  OK,下面是效果图:

 

 

 

 

 
posted @ 2016-03-16 19:11  南冥  阅读(174)  评论(0编辑  收藏  举报