内容居中的响应式圆圈

Responsive circle with centered content

有没有办法做到以下几点:

#id {
  border-radius: 100px;
  width: 100px;
  height: 100px;
}
<div id="circle">
  <h3>Hello</h3>
</div>

A round div,文本在垂直和水平方向居中。同时保持圈子响应。
我的意思是说包含 divwidth50%,同时保持 height 百分比相等以形成一个圆圈。

然后将静态 100px 更改为百分比,使圆变成椭圆形。

您可以制作一个内容居中的圆圈

  • padding-bottom 根据圆的宽度保持圆的纵横比 (more info here)
  • transform:translate(-50%,-50%); 使用绝对定位使内容在圆圈中垂直和水平居中(参见 this answer 中的方法 1)

.circle{
  position:relative;
  width:50%;
  padding-bottom:50%;
  background:gold;
  border-radius:50%;
}
.circle h3{
  position:absolute;
  top:50%; left:50%;
  transform: translate(-50%, -50%);
  margin:0;
}
<div class="circle">
  <h3>Hello</h3>
</div>

请注意,您需要将供应商前缀添加到转换 属性 以最大化浏览器支持(有关详细信息,请参阅 canIUse)。

视口单位

如果您使用相同的视口单位(vwvh),那么您应该会得到一个响应圆。

100 的视口单位将是宽度或高度的 100%。因此它与使用百分比非常相似。

div {
  width: 10vw;
  height: 10vw;
  border-radius: 50%;
  background: blue;
}
<div></div>

CSS 对此有 aspect-ratio 属性,它适用于元素的宽度和高度。

web 的更多内容:https://developer.mozilla.org/en-US/docs/Web/CSS/aspect-ratio

React Native的更多信息:https://reactnative.dev/docs/layout-props#aspectratio

.circle {
  width: 100%;
  border-radius: 50%;
  color: white;
  background-color: blue;
  text-align: center;
  aspect-ratio: 1 / 1;
}