border实现三角形的原理

前言:网上最普遍的实现三角形的方法,就是通过控制border来实现,那为什么可以呢?

原理

我们先来看看border的表现形式。

#box{
  width:100px;
  height:100px;
  background:yellow;
  border-top: 20px solid red;
  border-right:20px solid black;
  border-bottom:20px solid green;
  border-left:20px solid blue;
}

image

观察上图可以发现,border表现为梯形。当减小box的宽高时,会发生如下变化:

image

从上图很容易看出,当box宽度降低到很小,也就是border的梯形的上边降到很小。所以想一想,当这一值降到0时,border就变成了三角形。如下图:

image

所以我们就可以通过将元素宽高设置为0,而通过控制border来得到想要的三角形了。

实现

将不需要方向的border设置为透明(transparent),就可以用来实现三角形了。比如想实现下三角形,就将border-left,border-bottom,border-right设置为transparent即可。

#box{
  width:0px;
  height:0px;
  border-top: 20px solid red;
  border-right:20px solid transparent;
  border-bottom:20px solid transparent;
  border-left:20px solid transparent;
}

image

#box{
  width:0px;
  height:0px;
  border-top: 20px solid red;
  border-right:20px solid transparent;
  border-bottom:20px solid transparent;
  border-left:20px solid red;
}

 

image

#box{
  width:0px;
  height:0px;
  border-top: 60px solid red;
  border-right:20px solid transparent;
  border-bottom:0px solid transparent;
  border-left:20px solid transparent;
}

image

#box{
  width:100px;
  height:100px;
  border-top: 60px solid red;
  border-right:20px solid transparent;
  border-bottom:0px solid transparent;
  border-left:20px solid transparent;
}

image

 

就不一一列举了,只要明白每个方向的border都是一个三角形,就能通过调整border的大小和颜色/透明,获得各种三角形和梯形了。

转载于:https://www.cnblogs.com/youhong/p/6530575.html

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值