如何在包含div内对齐图像?

实例

在我的示例中,我需要使用class=“frame”将<img>垂直居中放置在<div>中:

<div class="frame" style="height: 25px;">
    <img src="http://jsfiddle.net/img/logo.png" />
</div>

.frame的高度是固定的,图像的高度是未知的。如果这是唯一的解决方案,我可以在.frame中添加新元素。我正在尝试在Internet Explorer 7和更高版本WebKit、Gecko上执行此操作。

看到这里的jsfiddle。

.框架{高度:25px;/*等于最大图像高度*/线条高度:25px;宽度:160px;边框:1px纯红色;文本对齐:居中;边距:1em 0;}国际货币基金组织{背景:#3A6F9A;垂直对齐:中间;最大高度:25px;最大宽度:160px;}<div class=frame><img src=“http://jsfiddle.net/img/logo.png“高度=250/></div><div class=frame><img src=“http://jsfiddle.net/img/logo.png“高度=25/></div><div class=frame><img src=“http://jsfiddle.net/img/logo.png“高度=23/></div><div class=frame><img src=“http://jsfiddle.net/img/logo.png“高度=21/></div><div class=frame><img src=“http://jsfiddle.net/img/logo.png“高度=19/></div><div class=frame><img src=“http://jsfiddle.net/img/logo.png“高度=17/></div><div class=frame><img src=“http://jsfiddle.net/img/logo.png“高度=15/></div><div class=frame><img src=“http://jsfiddle.net/img/logo.png“高度=13/></div><div class=frame><img src=“http://jsfiddle.net/img/logo.png“高度=11/></div><div class=frame><img src=“http://jsfiddle.net/img/logo.png“高度=9/></div><div class=frame><img src=“http://jsfiddle.net/img/logo.png“高度=7/></div><div class=frame><img src=“http://jsfiddle.net/img/logo.png“高度=5/></div><div class=frame><img src=“http://jsfiddle.net/img/logo.png“高度=3/></div>


当前回答

如果您可以使用像素大小的边距,只需添加字体大小:1px;但请记住,现在在.frame 1em=1px上,这意味着您也需要设置像素的边距。

http://jsfiddle.net/feeela/4RPFa/96/

现在它不再以歌剧为中心了…

其他回答

此外,您可以使用Flexbox获得正确的结果:

.父级{对齐项目:居中;/*用于垂直对齐*/背景:红色;显示:柔性;高度:250px;/*对齐内容:中心;<-用于水平对齐*/宽度:250px;}<div class=“parent”><img class=“child”src=“https://cdn2.iconfinder.com/data/icons/social-icons-circular-black/512/stackoverflow-128.png" /></div>

flexbox有一个超级简单的解决方案!

.frame {
    display: flex;
    align-items: center;
}

只是为了这是一个有效的答案,我仍然希望再次发布jQuery解决方案。这适用于应用了v_align类的每个元素。它将在父元素中垂直居中,在调整窗口大小时将重新计算。

链接到JSFiddle

$(document).ready(function() {
  // Define the class that vertically aligns stuff
  var objects = '.v_align';
  // initial setup
  verticalAlign(objects);

  // Register resize event listener
  $(window).resize(function() {
    verticalAlign(objects);
  });
});

function verticalAlign(selector) {
  $(selector).each(function(val) {
    var parent_height = $(this).parent().height();
    var dif = parent_height - $(this).height()
    // Should only work if the parent is larger than the element
    var margin_top = dif > 0 ? dif/2 : 0;
    $(this).css("margin-top", margin_top + "px");
  });
}

您可以尝试以下代码:

.框架{显示:柔性;对齐内容:中心;对齐项目:居中;宽度:100%;}<div class=“frame”style=“height:25px;”><img src=“http://jsfiddle.net/img/logo.png" /></div>

背景图像解决方案

我完全删除了image元素,并使用.frame类将其设置为div的背景

http://jsfiddle.net/URVKa/2/

这至少在Internet Explorer 8、Firefox 6和Chrome 13上运行良好。

我检查过了,这个解决方案无法缩小超过25像素高度的图像。有一个名为backgroundsize的属性可以设置元素的大小,但CSS 3会与Internet Explorer 7的要求相冲突。

我建议你要么重做你的浏览器优先级,为最好的可用浏览器设计,要么获取一些服务器端代码来调整图像大小,如果你想使用这个解决方案。