微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在CSS中创建边框角间距

如何使用CSS创建边界角间距,如下图所示?内容的高度不固定.

解决方法

使用 border-image

我们可以利用border-image在所有四个边上分配线性渐变作为边界图像.我们需要一个伪元素(与父容器重叠),因为渐变只能在一个方向上进行.梯度可以支持基于百分比的值,因此可以适应不同的容器尺寸.这可以通过将鼠标悬停在代码段中的div来验证.

这种方法的主要缺点是border-image属性low browser support.但是当只需要支持IE11时它非常有用,因为与Box-shadow不同,它不需要固定的尺寸,也不像clip-path那样复杂.还为其他潜在用途留下了备用伪元素.

.border-spacing{
  position: relative;
  height: 100px;
  width: 300px;
  padding: 10px;
  background: rgb(187,103,224);
  background-clip: content-Box;
  border-image: linear-gradient(to bottom,transparent 25%,black 15%,black 75%,transparent 75%);
  border-image-slice: 4;
  border-image-width: 4px;
  border-image-repeat: round;
  
  /* Just for demo */
  text-align: center;
  line-height: 100px;
  color: white;
}
.border-spacing:after{
  position: absolute;
  content: '';
  top: -2px; /* half of border-image-slice */
  left: -2px; /* half of border-image-slice */
  height: calc(100% - 20px); /* 100% - 2 * padding */
  width: calc(100% - 20px); /* 100% - 2 * padding */
  padding: 10px;
  border-image: linear-gradient(to right,transparent 75%);
  border-image-slice: 4;
  border-image-width: 4px;
  border-image-repeat: round;  
}

/* Just for demo */

.border-spacing{
  transition: all 1s;
}
.border-spacing:hover{
  height: 150px;
  width: 450px;
  line-height: 150px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/prefixfree/1.0.7/prefixfree.min.js"></script>
<div class="border-spacing">Content div</div>

使用background-image

我们可以利用background-image在所有四个边上分配线性渐变作为边界图像.我们需要一个伪元素(与父容器重叠),因此可以适应不同的容器尺寸.这可以通过将鼠标悬停在代码段中的div来验证.

这种方法的缺点也与之前的方法非常相似,因为linear-gradient仅受IE10支持.优点与前面提到的相同.

.border-spacing{
  position: relative;
  height: 100px;
  width: 300px;
  padding: 10px;
  background-image: linear-gradient(to bottom,transparent 75%),linear-gradient(to bottom,linear-gradient(to right,transparent 75%);
  background-size: 4px 100%,4px 100%,100% 4px,100% 4px;
  background-position: 0px 0px,100% 0px,0px 0px,0px 100%;
  background-repeat: no-repeat;
  
  /* Just for demo */
  text-align: center;
  line-height: 100px;
  color: white;
}
.border-spacing:after{
  position: absolute;
  content: '';
  top: 10px;
  left: 10px;
  height: calc(100% - 20px);
  width: calc(100% - 20px);
  z-index: -1;
  background: rgb(187,224);
}


/* Just for demo */

.border-spacing{
  transition: all 1s;
}
.border-spacing:hover{
  height: 150px;
  width: 450px;
  line-height: 150px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/prefixfree/1.0.7/prefixfree.min.js"></script>
<div class="border-spacing">Content div</div>

原文地址:https://www.jb51.cc/css/215651.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。