首页 > 解决方案 > 围绕可变高度的 div 画一个完美的圆圈

问题描述

我对此进行了相当多的研究,但似乎找不到一个好的、可靠的答案来找到如何围绕可变高度的 div 元素制作一个响应圈。

vw使用单位很容易制作一个简单的响应圈。

<div style="height:20vw; width:20vw"></div>

但是,我希望使用元素的最小高度并在这个 div 周围有一个圆圈。

创建响应圈的另一种方法是使用类似下面的代码片段,但我不能再调整它以适用于可变高度(同样,我不能使用vh单位,因为 div 会改变高度。

.square {
  position: relative;
  width: 10%;
  background: gray;
  border-radius: 50%;
}

.square:after {
  content: "";
  display: block;
  padding-bottom: 100%;
}

.content {
  position: absolute;
  width: 100%;
  height: 100%;
}
<div class="square">
  <div class="content">

  </div>
</div>

我正在尝试创建类似下面的内容,其中圆圈永远不会切入 div 的角落(大约 10px 填充)。我个人试图避免使用 javascript,并且更喜欢仅使用 css 的方法,但这似乎是不可避免的。也许唯一的解决方案是使用 jquery 来计算元素的高度,以便将其应用于包装元素?

在此处输入图像描述

我在玩这个:

.square {
  position: absolute;
  top: 50%;
  display: inline-block;
  left: 50%;
  transform: translate(-50%, -50%);
  min-height: 100px;
  border-radius: 50%;
  background: url('https://i.imgur.com/2dxaFs9_d.webp?maxwidth=640&shape=thumb&fidelity=medium');
  background-size: 100% 100%;
  padding: 20px;
}

.content {
  width: 300px;
  min-height: 100px;
  background: tomato;
}
<div class="square">
  <div class="content">
    Hello!<br>
    <br><br><br>This has a variable height but fixed width<br><br><br>Hello
  </div>
</div>

标签: htmljquerycss

解决方案


Clip-path如果您考虑纯色,则可以轻松做到这一点。

调整元素的大小,圆圈将跟随:

.box {
  width: 200px;
  height: 200px;
  overflow: hidden;
  resize: both;
  background: blue;
  box-shadow: 0 0 0 200vmax red;
  clip-path: circle(71%);
  margin: 100px auto;
}
<div class="box"></div>

了解幻数的相关问题71%clip-path:circle() 半径似乎没有正确计算


要使用图像,我们可以考虑伪元素。您还可以依靠calc()添加偏移量:

.box {
  width: 200px;=
  resize: both;
  clip-path: circle(calc(71% + 10px));
  margin: 100px auto;
  position: relative;
  font-size:35px;
  color:#fff;
}
/* the background layer */
.box::before {
  content:"";
  position: absolute;
  z-index:-1;
  top:0;
  left:0;
  right:0;
  bottom:0;
  background:blue;
}

/* the image layer */
.box::after {
  content:"";
  position: fixed; /* to make sure the image cover all the screen */
  z-index:-2;
  top:0;
  bottom:0;
  left:0;
  right:0;
  background:url(https://picsum.photos/id/1015/1000/1000) center/cover no-repeat;
}
<div class="box" contenteditable="true"> Edit this<br>text </div>


推荐阅读