方形有圆角和凹进弯曲的边框

vwe*_*tje 16 css svg border css3 css-shapes

我想知道是否有可能在纯CSS中制作一个带圆角的方形和一个缩进的边框.

目前我有这个:

#custom-square {
     position: relative;
     display: block;
     width: 75px;
     height: 75px;
     border: 2px solid #8A6EF1;
     border-radius: 10px;
     background-color: white;
}
Run Code Online (Sandbox Code Playgroud)

Squarez圆角和缩进边框

web*_*iki 13

考虑到将双曲线与CSS对齐所需的代码麻烦和数量,SVG似乎更合适.在这里寻找svg的其他一些原因是:

  • 控制路径(颜色,宽度,曲线......)
  • 用纯色,渐变或图像控制填充
  • 更少的代码
  • 你可以在非普通背景(渐变或图像)上显示它
  • 维护用户交互形状的边界(悬停,点击......)

这是使用带有path元素内联svg的基本示例. 使用Cubic Bezier曲线绘制曲线:

svg{width:30%;}
Run Code Online (Sandbox Code Playgroud)
<svg viewbox="0 0 10 10">
  <path d="M1.5 0.5 Q5 1 8.5 0.5 Q9.5 0.5 9.5 1.5 Q9 5 9.5 8.5 Q9.5 9.5 8.5 9.5 Q5 9 1.5 9.5 Q0.5 9.5 0.5 8.5 Q1 5 0.5 1.5 Q0.5 0.5 1.5 0.5z" 
        fill="none" stroke-width="0.2" stroke="#8A6FF2" />
</svg>
Run Code Online (Sandbox Code Playgroud)


Har*_*rry 5

另一种用于创建此边界的纯CSS方法是使用border-image属性.所需的只是创建具有所需边框形状的图像,并使用该border-image-source属性将其设置为元素.

.shape.large {
  height: 300px;
  width: 300px;
  border-image-source: url(http://i.stack.imgur.com/Qkh6A.png);
  border-image-width: 34px; /* the width of the border portions in the image - refer to image at the end of the answer for the exact portion details*/
  border-image-slice: 34; /* equal to border-image-width */
  border-width: 34px; /* equal to border-image-width */
}
.shape.small {
  height: 100px;
  width: 100px;
  border-image-source: url(http://i.stack.imgur.com/Mra4B.png);
  border-image-width: 14px;
  border-image-slice: 14;
  border-width: 14px;
}
.shape.small.fill {
  background: aliceblue content-box;
  border-image-source: url(http://i.stack.imgur.com/Ovj03.png);
  border-width: 14px;
}

/* Just for demo */

body {
  background: url(http://lorempixel.com/800/800/abstract/2);
}
.shape.small {
  float: left;
}
.shape.large {
  clear: both;
}
Run Code Online (Sandbox Code Playgroud)
<div class='shape small'>Some content</div>
<div class='shape small fill'>Some content</div>
<div class='shape large'>Some content</div>
Run Code Online (Sandbox Code Playgroud)

目前这种方法与SVG相比肯定没有太大的优势,但它是一种选择,在我看来比其他CSS方法更好.

这种方法的优点是:

  • 极低且复杂度极低的代码.
  • 更好地控制曲线及其半径(与SVG一样),因为可以单独创建具有所需边界曲率的图像.
  • 可以放在图像或渐变背景之上.
  • 可以在不支持它的浏览器中优雅地降级(变成实心方形边框).

缺点是:

  • 容器仍然是正方形,因此hover与SVG不同,效果不会局限于形状的边界.
  • 可以在图形中添加纯色填充(通过使用图像的填充版本),但添加渐变或图像填充是棘手的,因为边框仍然是块(即,曲线两侧都有透明区域).
  • 输出是响应的,但随着尺寸增大或减小超过阈值,形状开始看起来有点压缩或拉伸.因此,这更适合基于断点的设计.
  • 浏览器的支持是不坏,但不是很大无论是.它适用于Chrome,Firefox,Safari,Opera和IE11 +.

边界图像宽度的计算:

边框区域的宽度或高度(变为border-image-width)只不过是下图中突出显示的部分的宽度.

突出显示的部分定义边框图像宽度