[英]Vertical align block level element inside a block level element
I need to center align images (variable width and height) inside block level elements of fixed width and height. 我需要在固定宽度和高度的块级元素内对齐图像(可变宽度和高度)。 The css markup looks something like this:
css标记看起来像这样:
<div style="float: left; width: 100px; height: 100px;"><img src="yada" width="50" height="60"></div>
<div style="float: left; width: 100px; height: 100px;"><img src="yada" width="60" height="50"></div>
<div style="float: left; width: 100px; height: 100px;"><img src="yada" width="75" height="75"></div>
The point is, that the images align themselves to the top right corners of the container div. 关键是,图像将自己对齐到容器div的右上角。 I want them to be centered, both horizontally and vertically.
我希望它们在水平和垂直方向都居中。 I have tried setting the img tag style as follows:
我试过设置img标签样式如下:
img {
display: block;
margin: auto;
}
This center-aligns the img horizontally but not vertically. 这个中心 - 水平对齐img而不是垂直对齐。 I need both so that the gallery page looks neatly aligned.
我需要两个,以便画廊页面看起来整齐排列。 I need to avoid using tables at all cost although this produces the result exactly as I need.
我需要不惜一切代价避免使用表,尽管这会产生我想要的结果。 I need a portable, hack-less CSS solution.
我需要一个便携式,无黑客的CSS解决方案。
Yes, vertical margins are calculated in a fundamentally different way to horizontal ones; 是的,垂直边距的计算方式与水平边距完全不同; 'auto' doesn't mean centering.
'auto'并不意味着居中。
Setting 'vertical-align: middle' on the image elements sort of works, but it only aligns them relative to the line box they're currently on. 设置“垂直对齐:中间”上的图像元素进行排序的工作,但它只是比对它们相对于线箱 ,他们目前正在对。 To make the line box the same height as the float, set 'line-height' on the container:
要使线框的高度与浮点数相同,请在容器上设置“line-height”:
<style>
div { float: left; width: 100px; height: 100px; line-height: 100px; }
div img { vertical-align: middle; }
</style>
You have to be in Standards Mode for this to work, because otherwise browsers render images-on-their-own as blocks instead of inline replaced elements in a text line box. 您必须处于标准模式才能使其正常工作,因为否则浏览器会将这些图像自身呈现为块而不是文本行框中的内联替换元素。
Unfortunately, IE (up to 7 at least) still keeps the block behaviour even in its attempt at a Standards Mode. 不幸的是,即使在尝试标准模式时,IE(至少7个)仍然保持阻止行为。 There is a technical reason for this, namely that IE is pants.
这有一个技术原因,即IE是裤子。
To persuade IE that you really mean it about the images being part of a text line, you have to add some text inside the div — even a normal space will do it, but you could also try a zero-width-space: 为了说服IE你真正意味着图像是文本行的一部分,你必须在div中添加一些文本 - 即使是普通的空间也会这样做,但你也可以尝试零宽度空间:
<div><img src="http://i.stackoverflow.com/Content/Img/stackoverflow-logo-250.png" width="50" height="60" />​</div>
<div><img src="http://i.stackoverflow.com/Content/Img/stackoverflow-logo-250.png" width="60" height="50" />​</div>
<div><img src="http://i.stackoverflow.com/Content/Img/stackoverflow-logo-250.png" width="75" height="75" />​</div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.