我需要在固定宽度和高度的块级元素内居中对齐图像(可变宽度和高度)。 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>
要点是,图像将自身与容器 div 的右上角对齐。 我希望它们水平和垂直居中。 我尝试按如下方式设置 img 标签样式:
img {
display: block;
margin: auto;
}
这使 img 水平居中,但不垂直居中。 我需要两者,以便图库页面看起来整齐对齐。 我需要不惜一切代价避免使用表格,尽管这会产生完全符合我需要的结果。 我需要一个可移植、无黑客攻击的 CSS 解决方案。
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:
<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. I want them to be centered, both horizontally and vertically. I have tried setting the img tag style as follows:
img {
display: block;
margin: auto;
}
This center-aligns the img horizontally but not vertically. 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.
发布评论
评论(1)
是的,垂直边距的计算方式与水平边距的计算方式根本不同; “自动”并不意味着居中。
在图像元素上设置“vertical-align: middle”是可行的,但它只能相对于 线路盒。 要使行框与浮动高度相同,请在容器上设置“line-height”:
您必须处于
不幸的是,IE(至少 7)仍然保持阻止行为,即使在尝试标准模式时也是如此。 这有一个技术原因,即 IE 是裤子。
为了说服 IE 你真的认为图像是文本行的一部分,你必须在 div 内添加一些文本 - 即使是普通的空格也可以做到这一点,但你也可以尝试零宽度空格:
Yes, vertical margins are calculated in a fundamentally different way to horizontal ones; ‘auto’ doesn't mean centering.
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:
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. There is a technical reason for this, namely that IE is pants.
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: