响应式的圆形,带有居中的内容。

14

有没有办法让以下内容:

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

一个圆形的 div ,文字在垂直和水平方向上居中。同时保持圆圈的响应式。
我的意思是让它有一个例如包含元素宽度的50%width,同时保持height以相同的百分比使其成为圆形。

将静态的100px更改为百分比会使圆变成椭圆。


如果可以按比例缩放,您可以使用vwvh单位。示例 - insertusernamehere
@Paulie_D 我认为这个问题不能被关闭为纵横比问题的重复。制作圆形的方法是相同的,但似乎不足以成为重复(内容居中和它是一个圆形的事实)。 - web-tiki
1
答案完全相同,填充比率和视口单位。只是重复...其他任何东西都是边框半径和布局。 - Paulie_D
@Paulie_D,我认为这个问题值得保留的原因是它结合了纵横比和“其他任何事物”的部分。我认为,如果有人寻找一个带有居中内容的响应式圆形,单独在纵横比问题或内容居中问题中都不会找到合适的答案。 - web-tiki
经过2年的时间,这里有一个答案,展示了一个响应式圆圈,适应内容长度(请参见“随内容调整大小-改进”下的最后一个链接)。 - Jose Rui Santos
5个回答

22
您可以使用以下方法创建一个带有居中内容的圆形:

.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>

注意,您需要添加供应商前缀到 transform 属性以最大化浏览器支持(请参见 canIUse 了解更多信息)。


21

视口单位

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

100视口单位将是宽度或高度的100%。因此,这非常类似于使用百分比。

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


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

2

0

@media规则用于媒体查询,以应用不同的样式/大小/宽度/高度,适用于不同的媒体类型/设备。

媒体查询可用于检查许多内容,例如:

视口的宽度和高度 设备的宽度和高度 方向(平板电脑/手机是横向还是纵向模式?) 分辨率

请参见以下示例:

    /* Mobile & small screen size devices*/
    @media only screen and (max-width: 600px) {
            .circle {
            width: 210px!important;
            height: 210px!important;
        }
    }

    /* Desktop, Laptop, Tablet */
    @media only screen and (min-width: 650px) {
        .circle {
            width: 356px;
            height: 356px;
        }
    }

    .circle {
        margin: auto;
        width: 356px;
        height: 356px;
        opacity: 1;
        border-radius: 50%;
        background-color: gray;
    }
<div class="circle"></div>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接