请运行演示:
* {
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;
}
根据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高度。所以,我发现了这个:
所以,由于图像的存在,我认为在这种情况下父级的x高度不是第二条红线。
所以,我的问题是:
在这种情况下,父级的 x 高度是多少?是否因为图像的存在而改变?
或者还有什么问题吗?
请注意:
在这种情况下我只想获取
x-height
值,这样我就可以更好地理解vertical-align
。我并不是要求具体的解决方案。
无论如何,感谢您的帮助!
最佳答案
首先,元素的x-height
不受图像影响,仅由font-size
以及font-family定义
使用过。然后,为了获取 x-height
的值,您需要考虑 ex
单位。
这是为 this answer 拍摄的更好的插图。
您可以清楚地看到垂直对齐的每个值之间的差异,并且还注意到em
和ex
单位的图示。现在,为了获得 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>
如您所见,我使用 ex
和 em
单位添加了左右边框,然后如果我检查计算值,我可以获得准确的值。您还会注意到,两个 span
具有相同的值,这表明图像对其没有影响。
关于html - 带有图像垂直对齐的内联框 :middle with parent box,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50407494/