垂直对齐的内联块元素未在容器内完美居中 [英] Vertically-aligned inline-block element not perfectly centered within container

查看:43
本文介绍了垂直对齐的内联块元素未在容器内完美居中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 vertical-align:middle 在某些文本中垂直居中放置 inline-block 元素.

I'm trying to use vertical-align: middle to vertically center an inline-block element within some text.

p {
  background: red;
  line-height: 20px;
  display: block;
}

span {
  height: 18px;
  width: 18px;
  display: inline-block;
  background: lightblue;
  vertical-align: middle;
}

<p>
  <span></span>
  &lt;-- Not perfectly aligned
</p>

请注意,该元素未完全居中...为什么会这样?这是浏览器的一个问题吗?它可以在WebKit浏览器(Chrome,Safari)上进行再现.

Notice that the element isn't perfectly centered... why is this? Is this a browser off-by-one issue? It repros on WebKit browsers (Chrome, Safari).

推荐答案

vertical-align:middle; 从未打算将元素居中.这是一个更简单的示例,可以更好地了解:

vertical-align: middle; was never meant to center the element. Here is a more trivial example to better see:

p {
  background: 
    linear-gradient(yellow,yellow) center/100% 1px no-repeat, /* the center */
    red;
  line-height: 80px;
  font-size:80px;
  display: block;
}

span {
  height: 18px;
  width: 18px;
  display: inline-block;
  background: lightblue;
  vertical-align: middle;
}

<p>
  <span></span>
  &lt;-- Not aligned
</p>

将元素的中间与基线对齐,再加上父元素的x高度的一半 有关更多详细信息的问题:

Related question for more details:

如何理解垂直对齐:-0.125em和垂直对齐:中间的区别?

垂直对齐无法在内联代码块上运行

垂直对齐可对齐除自我以外的所有内容

https://stackoverflow.com/a/54190413/8620333

这篇关于垂直对齐的内联块元素未在容器内完美居中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆