方法一:border
先看看四边 border 颜色不同且不透明时的效果:
.rect1 { ???width: 0px; ???height: 0px; ???margin: auto; ???border: 20px solid red; ???border-left-color: blue; ???border-right-color: yellow; ???border-top-color: purple;}.rect2 { ???width: 0px; ???height: 0px; ???margin: auto; ???border-top: 20px solid red; ???border-left: 10px solid blue; ???border-right: 15px solid yellow; ???border-bottom: 25px solid purple;}.rect3 { ???width: 10px; ???height: 0px; ???margin: auto; ???border: 20px solid red; ???border-left-color: blue; ???border-right-color: yellow; ???border-top-color: purple;}.rect4 { ???width: 10px; ???height: 10px; ???margin: auto; ???border: 20px solid red; ???border-left-color: blue; ???border-right-color: yellow; ???border-top-color: purple;}<!--html--><div class=‘rect1‘></div><div class=‘rect2‘></div><div class=‘rect3‘></div><div class=‘rect4‘></div>
以上 rect1、rect3、rect4 个 div 的区别在于 width 和 height 的大小,而 rect2 的 4 边 border-width 值各不相同。
哈哈,三角形和梯形都出来啦。利用 border 属性,一个或多个元素可以组合出不同的图形。
除了 border 属性,还可以借助伪元素来实现三角形。
代码,demo
方法二:伪元素
看代码:
<!--css-->.pseudo-ele { ???width: 20px; ???height: 20px; ???background: transparent; ???overflow: hidden;}.pseudo-ele:after { ???display: block; ???width: 150%; ???height: 150%; ???content: ‘‘; ???background: red; ???transform: rotateZ(45deg) translateX(10px);}<!--html--><div class=‘pseudo-ele‘></div>
父元素需要设置 overflow: hidden,将伪元素超出范围的部分遮挡掉。
方法三:background
<!--css-->.linear { ???width: 30px; ???height: 30px; ???-webkit-background: linear-gradient(45deg, transparent 50%, red 50%, red 100%) ???background: linear-gradient(45deg, transparent 50%, red 50%, red 100%)}<!--html--><div class=‘linear‘></div>
通过渐变的方式,实现三角形,但是需要注意兼容性的问题。
还有最原始的方法,就是用三角形背景图啦。
参考:
《css揭秘》
css实现三角形
原文地址:http://www.cnblogs.com/xxhuan/p/7657726.html