CSS 三角型的实现原理

637 阅读1分钟

利用border来实现三角型

源码地址

注意:需要设置width:0,height:0

  • border的四个边框可以设置不同的颜色,存在4个三角

    border-top: 50px solid red; border-bottom: 50px solid green; border-left: 50px solid blue; border-right: 50px solid yellow;``

  • 从top开始取三角

border-top: 50px solid red; border-bottom: 50px solid transparent; border-left: 50px solid transparent; border-right: 50px solid transparent;

border-top: 50px solid transparent; border-bottom: 50px solid transparent; border-left: 50px solid transparent; border-right: 50px solid yellow;

border-top: 50px solid transparent; border-bottom: 50px solid green; border-left: 50px solid transparent; border-right: 50px solid transparent;

border-top: 50px solid transparent; border-bottom: 50px solid transparent; border-left: 50px solid blue; border-right: 50px solid transparent;

  • 设置三角边框

div:nth-child(2) span{ content: ""; display: block; width: 0; height: 0; top: -36px; position: relative; border-top: 50px solid transparent; border-bottom: 50px solid green; border-left: 50px solid transparent; border-right: 50px solid transparent; }

div:nth-child(2) span::before{ content: ""; display: block; width: 0; height: 0; position: absolute; top: -46px; left: -47px; border-top: 47px solid transparent; border-bottom: 47px solid yellow; border-left: 47px solid transparent; border-right: 47px solid transparent; }

  • 直角三角形(只需要设置一个水平边和一个垂直边)

content:""; width:0; height:0; position:absolute;/或设置display:block/ border-left: 50px solid yellow; border-bottom: 100px solid green;

设置width/height可以得到梯形

position: absolute; /或者设置display: block,若为inline类型,则为三角形/ width: 41px; height: 0; border-top: 30px solid transparent; border-bottom: 30px solid green; border-left: 30px solid transparent; border-right: 30px solid transparent;