[英]How to vertically center images of dynamic height inside a div of fixed height?
[英]How to vertically align an image inside a div with dynamic height?
我們有一個包含用戶上傳圖像的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中使用動態圖像的解決方案。 某些解決方案要求您知道圖像的尺寸。
有人有這個問題並解決了嗎?
您需要使用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%;
}
div.container_img {
display: table-cell;
vertical-align: middle;
/* other attributes */
}
有效,但我不確定它是否適用於所有IE版本。
您可以使用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%;
}
我認為你無法使用任何直接技術垂直對齊圖像。 你可以看到這個水平對齊圖像...
我知道這是一個古老的問題,但我認為只有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;
}
而已!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.