如何在CSS中垂直对齐所有文本?

问题描述 投票:7回答:4

问题似乎是某些字母,例如gyq等,其尾巴向下倾斜,因此不允许垂直居中。这是展示问题a的图像。

绿色框中的字符基本上是完美的,因为它们没有向下的尾巴。红色框中的内容演示了问题。

我希望所有字符都完美地垂直居中。在图像中,尾巴向下的字符未垂直居中。这可以纠正吗?

Here is the fiddle that demonstrates the problem in full

.avatar {
    border-radius: 50%;
    display: inline-block;
    text-align: center;
    width: 125px;
    height: 125px;
    font-size: 60px;
    background-color: rgb(81, 75, 93);
    font-family: "Segoe UI";
    margin-bottom: 10px;
}

.character {
    position: relative;
    top: 50%;
    transform: translateY(-50%);
    line-height: 100%;
    color: #fff;
}
<div class="avatar">
  <div class="character">W</div>
</div>

<div class="avatar">
  <div class="character">y</div>
</div>
javascript html css vertical-alignment
4个回答
0
投票
据我所知,要使其具有原生可伸缩性(即%vwvh值而不是pxem,这将是最困难的)。如果您需要使它在手机或平板电脑上看起来很漂亮,请考虑将我的解决方案与@media断点一起使用。

我的解决方案实质上是检测它是否是

lowercase元素

有尾巴,并添加一个类以补偿高度以补偿尾巴。

在我的测试中,对于capital字母或

小写字母

字母无尾巴,似乎不需要任何其他处理程序。如果我错了,请随时纠正我。如果您想弄乱并更改/测试此解决方案,请输入JSFiddle。>>

var circles = document.getElementsByClassName('circle'); var tails = ['q', 'y', 'p', 'g', 'j'] ; Array.from(circles).forEach(render); function render(element) { if(element.innerText == element.innerText.toLowerCase() && tails.includes(element.innerText)) { element.className += " scale"; } }
.circle { height: 150px; width: 150px; background-color: #bbb; border-radius: 50%; display: inline-block; text-align: center; vertical-align: middle; line-height: 150px; font-size: 50px; } .scale { line-height: 135px; }
<div>
  <div class="circle">W</div>
  <div class="circle">X</div>
</div>
<div>
  <div class="circle">y</div>
  <div class="circle">t</div>
</div>
让我知道您的想法,如果我错过了任何事情。最终解决方案很不错,因为我过去也遇到过类似的问题!

0
投票

-1
投票
© www.soinside.com 2019 - 2024. All rights reserved.