Html 垂直对齐 <p> 内的 img 和文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5219324/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Vertical align img and text inside <p>
提问by raklos
I can't get the img and text in the span to be vertically aligned:
我无法让跨度中的 img 和文本垂直对齐:
<p class="login-button">
<input type="submit" id="login-submit" value="Log On" /><img style="padding-left:20px;" id="loadingDiv" src="/Content/ib/images/ajax-loader.gif" />
<span id="error" style="color:red; padding-left:13px;">text </span>
</p>
Any ideas? I tried:
有任何想法吗?我试过:
.login-button{ vertical-align:middle; height:30px; line-height:30px;}
.login-button img{ vertical-align:middle;}
回答by Marc Audet
I set up a demo for your at: http://jsfiddle.net/audetwebdesign/dCAkx/
我为您设置了一个演示:http: //jsfiddle.net/audetwebdesign/dCAkx/
I simplified your CSS a tiny bit and added some background color and padding.
我稍微简化了你的 CSS 并添加了一些背景颜色和填充。
You need to apply the vertical-align
property to all the inline elements that you want to align.
您需要将该vertical-align
属性应用于要对齐的所有内联元素。
The vertical-align
property is not inherited, so you need to apply it to all the relevant elements.
该vertical-align
属性不是继承的,因此您需要将其应用于所有相关元素。
You can apply padding and margins to control the spacing between the text and the image.
您可以应用填充和边距来控制文本和图像之间的间距。
You can experiment a bit by adjusting the line-height
of the container p
and also, try out other alignment values such as top, bottom, baseline.
您可以通过调整line-height
容器的 进行一些试验p
,也可以尝试其他对齐值,例如顶部、底部、基线。
This trick is worth mastering because it touches on a key concept of how the CSS box model works, and this pattern is very common, so a good trick to have in your CSS toolbox.
这个技巧值得掌握,因为它触及了 CSS 盒模型如何工作的一个关键概念,而且这种模式非常常见,因此是 CSS 工具箱中的一个好技巧。
回答by lawl0r
display:table-cell;
vertical-align:middle;
回答by Myles Gray
Here's a quick example:
这是一个快速示例:
You can easily mod the values to your needs.
您可以轻松地根据需要修改这些值。
I just added a wrapper div around the image and the span called wrap
我只是在图像周围添加了一个包装器 div,跨度称为 wrap
Then added this in the CSS:
然后在 CSS 中添加:
.wrap{
position:absolute;
top:50%;
height:240px; /* Make this whatever you want your height with */
margin-top:-120px; /* Negative half of the height */
}
回答by Mathias Bynens
vertical-align: middle
doesn't work on elements with display: block
. Make them display: inline
if possible, or display: table-cell
if not.
vertical-align: middle
不适用于带有display: block
. display: inline
如果可能,请制作它们,否则制作它们display: table-cell
。
Also, http://mathiasbynens.be/demo/center-vertically-inside-floatmight help.
另外,http://mathiasbynens.be/demo/center-vertically-inside-float可能会有所帮助。