为什么不垂直对齐:中间工作?然而,垂直对齐:顶部确实有效。
跨度{垂直对齐:中间;}<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>
当前回答
接受答案中使用的技术仅适用于单行文本(demo),而不适用于多行文本(demo),如这里所述。
如果有人需要将多行文本垂直居中放置到图像中,以下是几种方法(方法1和方法2受此CSS技巧文章启发)
方法#1:CSS表格(FIDDLE)(IE8+(犬))
CSS:
div {
display: table;
}
span {
vertical-align: middle;
display: table-cell;
}
方法#2:容器上的伪元素(FIDDLE)(IE8+)
CSS:
div {
height: 200px; /* height of image */
}
div:before {
content: '';
display: inline-block;
height: 100%;
vertical-align: middle;
margin-right: -0.25em; /* Adjusts for spacing */
}
img {
position: absolute;
}
span {
display: inline-block;
vertical-align: middle;
margin-left: 200px; /* width of image */
}
方法3:Flexbox(FIDDLE)(犬用)
CSS(上面的fiddle包含供应商前缀):
div {
display: flex;
align-items: center;
}
img {
min-width: 200px; /* width of image */
}
其他回答
实际上,在这种情况下非常简单:对图像应用垂直对齐。因为它都在一行中,所以它实际上是您想要对齐的图像,而不是文本。
<!-- 将“垂直对齐:中间”样式从span移动到img--><div><img style=“vertical align:middle”src=“https://via.placeholder.com/60x60“alt=”显示文本60 x 60的灰色图像“><span style=“”>有效</span></div>
在FF3中测试。
现在,您可以将flexbox用于这种类型的布局。
.box格式{显示:柔性;对齐项目:居中;}<div class=“box”><img src=“https://via.placeholder.com/60x60"><span style=“”>有效</span></div>
您可以做的另一件事是将文本的行高度设置为<div>中图像的大小。然后将图像设置为垂直对齐:中间;
这是最简单的方法。
不知道为什么它不在导航浏览器上显示,但我通常在尝试显示带有图像和居中文本的标题时使用这样的代码段,希望它有所帮助!
https://output.jsbin.com/jeqorahupo
<hgroup style="display:block; text-align:center; vertical-align:middle; margin:inherit auto; padding:inherit auto; max-height:inherit">
<header style="background:url('http://lorempixel.com/30/30/') center center no-repeat; background-size:auto; display:inner-block; vertical-align:middle; position:relative; position:absolute; top:inherit; left:inherit; display: -webkit-box; display: -webkit-flex;display: -moz-box;display: -ms-flexbox;display: flex;-webkit-flex-align: center;-ms-flex-align: center;-webkit-align-items: center;align-items: center;">
<image src="http://lorempixel.com/60/60/" title="Img title" style="opacity:0.35"></img>
http://lipsum.org</header>
</hgroup>
第二部分{显示:柔性;对齐项目:居中;}<div><img src=“http://lorempixel.com/30/30/“alt=”小img“/><span>它起作用了</span></div>
该代码适用于IE和FF:
<div>
<img style="width:auto; height:auto;vertical-align: middle;">
<span>It does work on all browsers</span>
</div>