首页 > Web开发 > 详细

css实现三角形

时间:2020-03-06 00:06:52      阅读:67      评论:0      收藏:0      [点我收藏+]

css 实现三角形

面试中被问到如何用css实现一个三角形,想了半天就就想到一个border的实现,考虑了到transform的实现,但是没想来怎么去做。晚上查了各种资料最终实现了三种css的写法。

1.border

网上最多也是最灵活的实现方式

技术分享图片

<div class="arrow-up">
</div>
<div class="arrow-down">
</div>
<div class="arrow-left">
</div>
<div class="arrow-right">
</div>
/*箭头向上*/
.arrow-up {
    width:0; 
    height:0; 
    border-left:30px solid transparent;
    border-right:30px solid transparent;
    border-bottom:30px solid red;
}    
 /*箭头向下*/
.arrow-down {
    width:0; 
    height:0; 
    border-left:20px solid transparent;
    border-right:20px solid transparent;
    border-top:20px solid #0066cc;
}
/*箭头向左*/
.arrow-left {
    width:0; 
    height:0; 
    border-top:30px solid transparent;
    border-bottom:30px solid transparent; 
    border-right:30px solid yellow; 
}
/*箭头向右*/
.arrow-right {
    width:0; 
    height:0; 
    border-top:50px solid transparent;
    border-bottom: 50px solid transparent;
    border-left: 50px solid green;
}

2.background的linear-gradient

技术分享图片

html:

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

css:

.triangle{
        width: 40px;
        height: 40px;
        background: linear-gradient(135deg, transparent 30px, #1e1e1e         0) top left, 
        linear-gradient(135deg, transparent 15px, #1e1e1e 0) top            right, 
        linear-gradient(0deg, transparent 0px, #1e1e1e 0) bottom            right,
         linear-gradient(135deg, transparent 15px, #1e1e1e 0) bottom            left;
        background-size: 50% 50%;
        background-repeat: no-repeat;
}

3.tranform

这个方式用了两个div,利用其中一个div遮住另一个旋转以后的正方形的一半来实现。

技术分享图片

html:

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

css:

    .square{
        width: 40px;
        height: 40px;
        overflow: hidden;
    }
    .triangle {
        width: 40px;
        height: 40px;
        background:black;
        transform: rotate(45deg) translate(-28px);
    }

2与3方式我只是尝试了实现直角三角形,但也算是css实现三角形的方式吧(笑)。

css实现三角形

原文:https://www.cnblogs.com/waterserver/p/12423716.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!