cat*_*use 10 html css jquery height vertical-alignment
我们有一个包含用户上传图像的div.这是代码:
HTML:
<div class="container_img">
<img height="120" width="150" src="[image name].jpg">
</div>
Run Code Online (Sandbox Code Playgroud)
CSS:
div.container_img {
overflow: hidden;
width: 150px;
height: 150px;
}
Run Code Online (Sandbox Code Playgroud)
我们的问题是,如果用户上传的图像高度小于150像素,则底部有一个很大的空间.因此,我们希望垂直对齐图像,使其看起来不像是浮动的.
我曾尝试在网上搜索解决方案,但我找不到一个可以在DIV中使用动态图像的解决方案.某些解决方案要求您知道图像的尺寸.
有人有这个问题并解决了吗?
Hus*_*ein 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%.
Run Code Online (Sandbox Code Playgroud)
CSS
div.container_img {
position:relative;
width: 150px;
height: 300px;
}
div.container_img img{
position:absolute;
top:50%;
}
Run Code Online (Sandbox Code Playgroud)