如何在div中垂直居中放置img? [英] How do I vertically center an img in a div?
问题描述
我有一个< img>
,我想在< div>
中居中.我在这里找到的所有以前的答案都使用了一些技巧,或者要求您知道图像的宽度,具体情况因我而异.
I have an <img>
that I want to center in a <div>
. All previous answers I've found here use some hack or require you to know the image's width, which varies in my case.
水平居中很容易.我不知道如何垂直对齐.
Horizontal centering with text-align: center
on the parent is easy. I can't figure out how to vertically align.
jsFiddle example
仅供参考,Facebook仅使用HTML和CSS就能做到这一点.因此,请不要使用< table>
或javascript hacks.似乎他们使用的是 line-height
的东西使他们的< img>
垂直居中.
FYI Facebook does this well using just HTML and CSS. So please no <table>
or javascript hacks. It looks like they are using something with line-height
to make their <img>
vertically center.
推荐答案
请记住, vertical-align:middle;
本身并没有用,您还需要设置line-height: line-height:400px;
.
Remember that vertical-align: middle;
is not to useful on its own, you also need to set the line-height: line-height:400px;
.
如果您的< div>
中没有其他文本(可能只有一行),这将很有用.
This is useful if you have no other text in your <div>
(except maybe a single line).
工作示例: http://jsfiddle.net/kobi/ZfMYy/5/
这篇关于如何在div中垂直居中放置img?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!