使用CSS实现可修改虚线长度的虚线边框

最近美工提了一个问题,能不能修改虚线边框的虚线长度?我一听满脸问号,我记得css的border不能设置虚线长度吧。抱着试一试的心态,我去stock overflow搜了一下,发现可以使用 background-image + background-position + background-size + background-repeat 实现这个需求。下面时一个简单的示例:

.dashed-top {
  width: 100px;
  height: 100px;
  background-color: #000;  
  background-image: linear-gradient(to right, rgba(255, 255, 255, 0.8) 50%, rgba(255, 255, 255, 0) 0%);
  background-position: top;
  background-size: 20px 1px;
  background-repeat: repeat-x;
}

该示例会绘制一个宽高为 100px 、背景色为黑色的方块,这个方块的顶部有一条白色的虚线。

实现了第一条,剩下的就简单了,只需复制粘贴并小小修改一下就能让这个方块被虚线包裹了。以下时实例代码:

.dashed-top {
  width: 100px;
  height: 100px;
  background-color: #000;  
  background-image: linear-gradient(to right, rgba(255, 255, 255, 0.8) 50%, rgba(255, 255, 255, 0) 0%),
    linear-gradient(rgba(255, 255, 255, 0.8) 50%, rgba(255, 255, 255, 0) 0%),
    linear-gradient(to left, rgba(255, 255, 255, 0.8) 50%, rgba(255, 255, 255, 0) 0%),
    linear-gradient(to top, rgba(255, 255, 255, 0.8) 50%, rgba(255, 255, 255, 0) 0%);
  background-position: top, right, bottom, left;
  background-size: 20px 1px, 1px 20px, 20px 1px, 1px 20px;
  background-repeat: repeat-x, repeat-y, repeat-x, repeat-y;
}

 

posted @ 2021-07-07 17:34  FreezeNow  阅读(2151)  评论(0编辑  收藏  举报