用 CSS 限制形状的边框

Limit Shape's Border with CSS

我需要达到 this demo 中的效果。

但是我在那里使用的代码太具体而且不是很干净。如您所见,我使用了相当多的元素以及一些具有非常特定角度计算的变换。

有没有办法让我创建这种形状,使其保持响应但更简洁? 请注意,我不想要半个圆,而是一个我可以适应的非常具体的角度。我的意思是圆可能或多或少在矩形内部,所以圆弧的角度或多或少会大。

CSS:

.rectangle {
  background-color: white;
  width:200px;
  height:200px;
  border:solid 1px navy;
}
.circle {
  position: relative;
  width: 70px; height: 70px;
  border-radius: 50%;
  background: white;
  margin-top:calc(50% - 35px);
  margin-left:calc(100% - 50px);
}
.arc {
  overflow: hidden;
  position: absolute;
  top: -1px; right: 50%; bottom: 50%; left: -1px;
  transform-origin: 100% 100%;
  transform: rotate(115deg);
}
.arc:before {
  box-sizing: border-box;
  display: block;
  border: solid 1px navy;
  width: 200%; height: 200%;
  border-radius: 50%;
  content: '';
}

.arc2 {
  overflow: hidden;
  position: absolute;
  top: -1px; right: 50%; bottom: 50%; left: -1px;
  transform-origin: 100% 100%;
  transform: rotate(155deg);
}
.arc2:before {
  box-sizing: border-box;
  display: block;
  border: solid 1px navy;
  width: 200%; height: 200%;
  border-radius: 50%;
  content: '';
}

HTML:

<div class='rectangle'>
  <div class='circle'>
    <div class='arc'></div>
    <div class='arc2'></div>
  </div>
</div>

注意事项:

  1. 我不能使用 z-index,这是我的第一个解决方案,但它会导致其他问题。
  2. 矩形的高度可以改变,所以我需要它响应,但即使容器的高度变大,圆的高度也应该保持不变
  3. 如果可以的话,我可以使用 SVG。

我通常建议对此类形状使用 SVG,因为使用它更容易创建和维护圆弧。使用 SVG 还意味着更好地控制半径、圆弧的开始和结束角度等,但我认为我们不能使形状的一部分(矩形)保持响应,同时保持其他部分为静态(圆的高度),因此使用 CSS.

可能更安全

同样,在 CSS 中,很难用单个元素实现这一点,因为您已经指出不能使用 z-index。其他方法(例如使元素的宽度大于高度或使用比例)会导致椭圆弧,并且还需要在高度或宽度变化时调整定位属性。

考虑到所有这些,下面使用几个元素和一个伪元素的方法可能是最好的选择。 .inner 元素位于 .rectangle 右边框的顶部,其宽度刚好足以显示圆圈。在 .inner 元素内,创建圆的伪元素以负向左偏移放置,因此只有圆的一部分可见(由于溢出在 .inner 上被隐藏)。输出响应。

.rectangle {
  position: relative;
  background-color: white;
  width: 200px;
  height: 200px;
  border: solid 1px navy;
}
.inner {
  position: absolute;
  left: 100%;
  top: -1px;
  height: calc(100% + 2px);
  width: 30px;
  overflow: hidden;
}
.inner:after {
  position: absolute;
  content: '';
  width: 70px;
  height: 70px;
  border-radius: 50%;
  background: white;
  top: calc(50% - 35px);
  left: -45px;
  border: 1px solid navy;
}

/* Just for demo */

.rectangle {
  transition: all 1s ease;
}
.rectangle:hover {
  height: 400px;
}
<div class='rectangle'>
  <div class="inner"></div>
</div>