css三角形绘制方法总结

在作UI(页面重构)的时候,免不了和各类小图标打交道,这其中最多的应该是三角形以及箭头,通常状况下能够经过伪类使用unicode解决大部分问题。css

如今咱们来总结下几种使用css绘制三角形的方法,dom结构以下:html

<div class="triangle"></div>

最简单最方便的办法 background

代码忽略

unicode

.triangle:after{
    display:block;
    content:"\25B2";
    color:"#fd5353";
    font-size:20px;
}

注意,伪类必须加上content属性,不然不生效css3

unicode图表web

border

.triangle{
    width: 0;
    height: 0;
    border-left: 50px solid transparent;
    border-right: 50px solid transparent;
    border-bottom: 100px solid red;
}

使用border绘制三角形是什么原理?事实上,宽度相等的border是以45度对接的,以下图:浏览器

image

那么没有了上border就是以下图:dom

image

再设置div的宽度为0,就是以下图:post

image

再设置div的高度为0,以下图:spa

image

最后设置左右border的颜色为透明,以下图:code

image

再来个动图:orm

image

经过这种原理,咱们能够作更多的图形,好比五角星、六角星等,更多图形请移步shapesofcss

使用css3 transform rotate

image

.triangle {
    width: 30%;
    padding-bottom: 21.27%; /* = width / 1.41 */
    position: relative;
    
    //划重点
    overflow:hidden;
}

.triangle: before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: #0079C6;
    
    //划重点
    transform-origin: 0 100%;        
    transform: rotate(45deg);
}

为何是1.41,由于正方形的对角线长度是约等于1.414。

使用clip-path

.triangle{
    width:200px;
    height:200px;
    background:#fd5353;
    clip-path: polygon(50% 0, 0 100%, 100% 100%);
}

clip-path不支持安卓4.4如下,其他均需使用浏览器前缀-webkit,caniuse

详细请移步 clip-path

原文

相关文章
相关标签/搜索