如何垂直对齐div内的图像与动态高度?

时间:2011-03-24 06:50:38

标签: jquery html css height vertical-alignment

我们拥有的div包含用户上传的图像。这是代码:

HTML:

<div class="container_img">
    <img height="120" width="150" src="[image name].jpg">
</div>

CSS:

div.container_img {
    overflow: hidden;
    width: 150px;
    height: 150px;
}

我们的问题是,如果用户上传的图片高度小于150像素,则底部有一个很大的空间。因此,我们希望垂直对齐图像,使其看起来不像是浮动的。

我尝试在网上搜索解决方案,但我找不到一个可以在DIV中使用动态图像的解决方案。有些解决方案要求您知道图像的尺寸。

有人有这个问题并解决了吗?

6 个答案:

答案 0 :(得分:10)

您需要使用JavaScript / jQuery来检测图像高度。 CSS不是动态语言,您无法使用纯CSS检测高度。使用jQuery你可以做到

<强>的jQuery

var $img = $('div.container_img img');
var h = $img.height();
$img.css('margin-top', + h / -2 + "px"); //margin-top should be negative half of image height. This will center the image vertically when combined with position:absolute and top:50%.

<强> CSS

div.container_img {
    position:relative; 
    width: 150px;
    height: 300px;
}

div.container_img img{
    position:absolute;
    top:50%;
}

检查http://jsfiddle.net/nQ4uu/2/

处的工作示例

答案 1 :(得分:1)

div.container_img {
    display: table-cell;
    vertical-align: middle;
    /* other attributes */
}

有效,但我不确定它是否适用于所有IE版本。

答案 2 :(得分:0)

我认为您无法使用任何直接技术垂直对齐图像。您可以看到this水平对齐图像...

答案 3 :(得分:0)

不是那么容易,请查看此页http://www.vdotmedia.com/demo/css-vertically-center.html

答案 4 :(得分:0)

您可以使用flex in css实现此目的:

div.container_img {
    position:flex; 
     width: 150px;
    height: 150px;
    justify-content: center;
}

div.container_img img{
  margin-top: auto;
  margin-bottom: auto;
  width: auto;
  height: auto;
  max-width: 100%;
  max-height: 100%;
}

答案 5 :(得分:-2)

我知道这是一个古老的问题,但我认为我只用CSS来回答问题

DEMO jsFiddle

HTML

 <div id="centered"></div>

CSS

#centered {
    position: fixed;
    top: 0;
    bottom: 0;
    right: 0;
    left: 0;
    height: 100px;
    width: 300px;
    margin: auto;
    background-color: grey;
}

就是这样!

相关问题