为什么不垂直对齐:中间工作?然而,垂直对齐:顶部确实有效。
跨度{垂直对齐:中间;}<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>
当前回答
在这些答案中还没有找到一个有余量的解决方案,所以这里是我对这个问题的解决方案。
只有当您知道图像的宽度时,此解决方案才有效。
HTML
<div>
<img src="https://placehold.it/80x80">
<span>This is my very long text what should align. This is my very long text what should align.</span>
</div>
CSS
div {
overflow:hidden;
}
img {
width:80px
margin-right:20px;
display:inline-block;
vertical-align:middle;
}
span {
width:100%;
margin-right:-100px;
padding-right:100px;
display:inline-block;
vertical-align:middle;
box-sizing:border-box;
-moz-box-sizing:border-box;
-webkit-box-sizing:border-box;
}
其他回答
我同意,这可能令人困惑。尝试利用表格功能。我使用这个简单的CSS技巧将情态动词放在网页的中心。它具有大型浏览器支持:
<div class="table">
<div class="cell">
<img src="..." alt="..." />
<span>It works now</span>
</div>
</div>
和CSS部分:
.table { display: table; }
.cell { display: table-cell; vertical-align: middle; }
请注意,您必须设置图像和表格容器的样式并调整其大小,以使其按您的需要工作。享受
您可以做的另一件事是将文本的行高度设置为<div>中图像的大小。然后将图像设置为垂直对齐:中间;
这是最简单的方法。
显示带对齐项目的柔性:居中;是垂直对齐项目的最佳方式
第二部分{显示:柔性;对齐项目:居中;}<div><img src=“https://via.placeholder.com/30“alt=”小img“/><span>它起作用</span></div>
以下是一些简单的垂直对齐技术:
单行垂直对齐:中间
这很简单:将文本元素的行高度设置为等于容器的行高度
<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%);
多线解决方案:
http://jsfiddle.net/zH58L/6/
<div style="display:table;width:30px;height:160px;">
<img style="display:table-cell;width:30px;height:60px;padding:50px" src='...' />
<div style="display:table-cell;height:30px;vertical-align:middle">
Multiline text centered vertically
</div>
</div>
<!-- note: img (height + 2x padding) must be equal to root div height -->
适用于所有浏览器和ie9+