居中对齐div

时间:2017-12-02 05:57:02

标签: css

对于我正在建设的网络论坛,我想使用用户的第一个字母'用户名作为头像(对于尚未上传头像的人)。

为了做到这一点,我先取出第一个字母,将其大写,然后围绕它绘制一个圆圈,使得该字母完美地出现在所述圆圈的中间。

我已经使用CSS来做到这一点。看看结果:

enter image description here

以下是不支持border-radius的浏览器的外观(例如Opera Mini):

enter image description here

请注意,我对于浏览器的平方结果没问题,其中' border-radius'不起作用。

问题:字母在形状内不完全居中对齐(垂直和水平)。

例如,如果我分别增加或减少字体大小,那么会发生什么:

enter image description here

enter image description here

enter image description here

如何确保字母在div 内水平和垂直居中对齐,而不管字体大小

请提供一个说明性示例,最好使用支持良好的CSS 2.1属性,因为我必须提供的大量客户端是具有CSS3或JS支持的Opera Mini浏览器。

以下是我尝试过的方法:



.av_btn {
  text-align: center;
  display: inline-block;
  border-radius: 50%;
  padding: 5px;
  background-color: white;
  font-weight: bold;
}

<div class="av_btn" style="border: 1px #1947D1 solid;width:22px;height:22px;">
  <b>M</b>
</div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

似乎(至少)部分问题是由于使用内联样式和CSS样式引起的。

heightwidth的内嵌样式被硬编码为固定像素值。虽然CSS值不定义font-size,但它使用浏览器或继承的字体大小)。要获得所需的结果,我们需要heightwidthline-heightfont-size匹配。

我建议将所有样式移动到单个来源 - 可以是内联或CSS。我将使用CSS获取以下解决方案。

我认为最好的解决方案是将line-heightwidthheight属性与使用em单位的值匹配。例如1.7em单位。

通过此设置,font-size可以更改为几乎任何内容,并且字母将放置在元素的中心。

以下是一个例子:

&#13;
&#13;
.av_btn {
  justify-content: center;
  align-content: center;
  display: inline-flex;
  border-radius: 50%;
  padding: 5px;
  font-size: 18px;
  line-height: 1.7em;
  width: 1.7em;
  height: 1.7em;
  background-color: white;
  font-weight: bold;
  border: 1px #1947D1 solid;
}
&#13;
<div class="av_btn">
  <b>M</b>
</div>
&#13;
&#13;
&#13;

以下是一个示例,说明它如何随字体大小缩放。

&#13;
&#13;
var size = document.getElementById("font-size");
var avatar = document.getElementById("avatar");

size.addEventListener("change", function(event) {
  var fontSize = event.target.value;
  avatar.style.fontSize = fontSize + "px";
})
&#13;
.av_btn {
  justify-content: center;
  align-content: center;
  display: inline-flex;
  border-radius: 50%;
  padding: 5px;
  font-size: 18px;
  line-height: 1.7em;
  width: 1.7em;
  height: 1.7em;
  background-color: white;
  font-weight: bold;
  border: 1px #1947D1 solid;
}
&#13;
<input id="font-size" type="range" min="16" max="100" value="16" /> 

<div class="av_btn" id="avatar">
  <b>M</b>
</div>
&#13;
&#13;
&#13;

相关问题