html - 带有图像垂直对齐的内联框 :middle with parent box

标签 html css vertical-alignment

请运行演示:

* {
  margin:0;
  padding:0;
}
.body {
  font-family:Microsoft Yahei;
  font-size:16px;
  background-color:lightblue;
  height: 200px;
  width:200px;
  line-height:2;
}
.body span {
  background-color:pink;  
}
.body img {
  width:50px;
  height:50px;
}
.body .img-wrapper {
  background-color:orange;
}
.body .img-wrapper {
  vertical-align:middle;
} 
<div class="body">
  <span class="wrapper">
      words-g words-g words-g
    <span class="img-wrapper">
      <img src="https://avatars3.githubusercontent.com/u/23273077" alt="">
        s
    </span>
    words-g words-g words-g
  </span>
</div>

重点是我设置

.body .img-wrapper {
      vertical-align:middle;
} 

我期望下图中的红线在同一行: enter image description here

根据specification ,

Align the vertical midpoint of the box with the baseline of the parent box plus half the x-height of the parent.

所以,我认为:

  • 盒子的垂直中点是上图中的第一条红线
  • 父框的基线加上父框x高度的一半=第二条红线

但事实证明我错了,我猜关键是父级的x高度。所以,我发现了这个: enter image description here

所以,由于图像的存在,我认为在这种情况下父级的x高度不是第二条红线。

所以,我的问题是:

  • 在这种情况下,父级的 x 高度是多少?是否因为图像的存在而改变?

  • 或者还有什么问题吗?

请注意:

  • 在这种情况下我只想获取x-height值,这样我就可以更好地理解vertical-align

  • 我并不是要求具体的解决方案。

无论如何,感谢您的帮助!

最佳答案

首先,元素的x-height不受图像影响,仅由font-size以及font-family定义 使用过。然后,为了获取 x-height 的值,您需要考虑 ex 单位。

这是为 this answer 拍摄的更好的插图。

Location of the baseline on text

您可以清楚地看到垂直对齐的每个值之间的差异,并且还注意到emex单位的图示。现在,为了获得 x-height 的精确值,您只需使用 ex 单位即可。

这是一个例子:

* {
  margin:0;
  padding:0;
}
body {
  font-family:Microsoft Yahei;
  font-size:16px;
  background-color:lightblue;
  line-height:2;
}
span {
  background-color:pink;  
  border-right:1ex solid red;
  border-left:1em solid red; 
}
img {
  width:50px;
  height:50px;
}
<span>
    words-g words-g words-g
</span>
<br>
<span>
    words-g words-g words-g <img src="https://avatars3.githubusercontent.com/u/23273077" alt="">
</span>

如您所见,我使用 exem 单位添加了左右边框,然后如果我检查计算值,我可以获得准确的值。您还会注意到,两个 span 具有相同的值,这表明图像对其没有影响。

enter image description here

关于html - 带有图像垂直对齐的内联框 :middle with parent box,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50407494/

相关文章:

javascript - jQuery 检测滚动条上的 div 位置

html - 如何在 div 框中制作不同的边框颜色?

html - 垂直对齐 : top two floated divs within container

Css - 将图像与底部对齐,垂直对齐不起作用

html - 在 Internet Explorer 中将子项与内联父项的顶部对齐

html - 由浏览器在 P 标签中生成

javascript - document.write 样式 css javascript

html - 用长字包裹表格单元格

javascript - 使用 Javascript 样式化元素而不被注意到

jquery - 单击响应菜单后效果过渡更平滑