简体   繁体   English

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

[英]How to vertically align an image inside a div with dynamic height?

What we have is a div that contains an image that a user uploads. 我们有一个包含用户上传图像的div。 This is the code: 这是代码:

HTML: HTML:

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

CSS: CSS:

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

Our problem is if the image the user uploads has a height smaller than 150px, there's a big space at the bottom. 我们的问题是,如果用户上传的图像高度小于150像素,则底部有一个很大的空间。 So we want to vertically align the image so that it doesn't look like it's just floating. 因此,我们希望垂直对齐图像,使其看起来不像是浮动的。

I've tried searching for solutions on the net but I can't find one that works with dynamic images inside a DIV. 我曾尝试在网上搜索解决方案,但我找不到一个可以在DIV中使用动态图像的解决方案。 Some solutions require that you know the dimensions of the image. 某些解决方案要求您知道图像的尺寸。

Has anybody had this problem and solved it? 有人有这个问题并解决了吗?

You need to use JavaScript/jQuery to detect image height. 您需要使用JavaScript / jQuery来检测图像高度。 CSS is not a dynamic language and you cannot detect height using pure css. CSS不是动态语言,您无法使用纯CSS检测高度。 Using jQuery you can do 使用jQuery你可以做到

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 CSS

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

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

Check working example at http://jsfiddle.net/nQ4uu/2/ 查看http://jsfiddle.net/nQ4uu/2/上的工作示例

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

works but I'm not sure if it does on all IE versions. 有效,但我不确定它是否适用于所有IE版本。

You can achieve this using flex in css: 您可以使用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%;
}

I think you won't be able to align the image vertically using any straight forward technique. 我认为你无法使用任何直接技术垂直对齐图像。 You can see this for aligning the image horizontally though... 你可以看到这个水平对齐图像...

这并不容易,请查看此页面http://www.vdotmedia.com/demo/css-vertically-center.html

I know this is an old question but i think there is abetter answer with CSS alone 我知道这是一个古老的问题,但我认为只有CSS才有更好的答案

DEMO jsFiddle DEMO jsFiddle

HTML HTML

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

CSS CSS

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

That's it! 而已!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM