如何仅使用CSS设置变形框的样式

时间:2020-10-12 20:37:17

标签: css

我正在考虑如何设计变形框:

enter image description here

我发现用伪元素和边界半径作为百分比可以达到相似的结果。 这是CodePen:https://codepen.io/micu22/pen/eYzpmqR 这是代码:

div {
  background: lightblue;
  padding: 10px 20px;
  border-radius: 8px;
  position: relative;
}
div::after,
div::before {
  content: "";
  position: absolute;
  background: white;
  width: 100%;
  height: 20px;
  left: 0;
}
div::before {
  top: -17px;
  border-radius: 50%;
}
div::after {
  bottom: -17px;
  border-radius: 50%;
}

但是也许有一个更简单或更优雅的解决方案?

2 个答案:

答案 0 :(得分:2)

我会像下面那样使用渐变色和SVG滤镜来做到这一点:

.box {
   width:200px;
   height:250px;
   background:
     /*                   v-- adjust the 15% here */
     radial-gradient(50% 15% at top,   transparent 98.5%,lightblue) top,
     radial-gradient(50% 15% at bottom,transparent 98.5%,lightblue) bottom;
   background-size:100% 51%;
   background-repeat:no-repeat;
   filter: url('#goo');
}
<div class="box"></div>

<svg style="visibility: hidden; position: absolute;" width="0" height="0" xmlns="http://www.w3.org/2000/svg" version="1.1">
    <defs>                                  <!-- adjust the the 13 here --v         -->
        <filter id="goo"><feGaussianBlur in="SourceGraphic" stdDeviation="13" result="blur" />    
            <feColorMatrix in="blur" mode="matrix" values="1 0 0 0 0  0 1 0 0 0  0 0 1 0 0  0 0 0 19 -9" result="goo" />
            <feComposite in="SourceGraphic" in2="goo" operator="atop"/>
        </filter>
    </defs>
</svg>

答案 1 :(得分:1)

这取决于内容将如何存在。如果这是一个固定高度的容器,我可能会选择使用SVG背景的解决方案。

我认为最优雅(或至少是固有的)解决方案涉及使用clipping paths.,这将使您能够创建所需形状的SVG并裁剪容器或容器的背景图片,以便并没有掩盖该元素在技术上仍然可见的部分。

Clippy是一个很棒的工具,如果您以前从未使用过剪切蒙版。