为什么不垂直对齐:中间工作?然而,垂直对齐:顶部确实有效。
跨度{垂直对齐:中间;}<div><img src=“https://via.placeholder.com/30“alt=”小img“/><span>不起作用</span></div>
为什么不垂直对齐:中间工作?然而,垂直对齐:顶部确实有效。
跨度{垂直对齐:中间;}<div><img src=“https://via.placeholder.com/30“alt=”小img“/><span>不起作用</span></div>
当前回答
您可以做的另一件事是将文本的行高度设置为<div>中图像的大小。然后将图像设置为垂直对齐:中间;
这是最简单的方法。
其他回答
您必须对两个元素应用垂直对齐:中间对齐,以使其完全居中。
<div><img style=“vertical align:middle”src=“http://lorempixel.com/60/60/">完美居中</span></div>
被接受的答案确实将图标置于旁边文本x高度的一半左右(如CSS规范中所定义)。这可能足够好,但如果文本在顶部或底部有上升部分或下降部分,则可能看起来有点偏离:
左侧的文本未对齐,右侧的文本如上图所示。在这篇关于垂直对齐的文章中可以找到一个实时演示。
有人讨论过为什么垂直对齐:顶部在场景中起作用吗?问题中的图像可能比文本高,因此定义了线框的顶部边缘。垂直对齐:在span元素的顶部,然后将其放置在线框的顶部。
垂直对齐:中间和顶部之间行为的主要区别在于,第一个相对于框的基线移动元素(将其放置在需要实现所有垂直对齐的位置,因此感觉相当不可预测),第二个相对于线框的外部边界移动元素(更为有形)。
使用行高度:30px作为跨度,以便文本与图像对齐:
<div>
<img style="width:30px; height:30px;">
<span style="line-height:30px;">Doesn't work.</span>
</div>
因为您必须将行高度设置为div的高度,这样才能工作
将div更改为flex容器:
div { display: flex; }
方法1:
div { align-items: center; }
DEMO
方法2:
div * { margin: auto 0; }
DEMO
尝试在img上使用不同的宽度和高度值,在跨距上尝试不同的字体大小值,您将看到它们始终保持在容器的中间。
以下是一些简单的垂直对齐技术:
单行垂直对齐:中间
这很简单:将文本元素的行高度设置为等于容器的行高度
<div>
<img style="width:30px; height:30px;">
<span style="line-height:30px;">Doesn't work.</span>
</div>
多行垂直对齐:底部
相对于容器绝对定位内部div
<div style="position:relative;width:30px;height:60px;">
<div style="position:absolute;bottom:0">This is positioned on the bottom</div>
</div>
多行垂直对齐:中间
<div style="display:table;width:30px;height:60px;">
<div style="display:table-cell;height:30px;">This is positioned in the middle</div>
</div>
如果您必须支持IE的早期版本<=7
为了让它在所有方面都能正常工作,你必须稍微修改一下CSS。幸运的是,有一个IE bug对我们有利。在容器上设置top:50%,在内部div上设置top:-50%,可以获得相同的结果。我们可以使用IE不支持的另一个功能将两者结合起来:高级CSS选择器。
<style type="text/css">
#container {
width: 30px;
height: 60px;
position: relative;
}
#wrapper > #container {
display: table;
position: static;
}
#container div {
position: absolute;
top: 50%;
}
#container div div {
position: relative;
top: -50%;
}
#container > div {
display: table-cell;
vertical-align: middle;
position: static;
}
</style>
<div id="wrapper">
<div id="container">
<div><div><p>Works in everything!</p></div></div>
</div>
</div>
可变容器高度垂直对齐:中间
此解决方案需要比其他解决方案稍微更现代的浏览器,因为它使用了transform:translateY属性。(http://caniuse.com/#feat=transforms2d)
无论父元素的高度如何,将以下3行CSS应用于元素将在其父元素中垂直居中:
position: relative;
top: 50%;
transform: translateY(-50%);