What we have is a div that contains an image that a user uploads. This is the code:
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;
}
Our problem is if the image the user uploads has a height smaller than 150px, there's a big space at the bottom. 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. Some solutions require that you know the dimensions of the image.
Has anybody had this problem and solved it?
When you have a block with fixed height (in px , em or another absolute unit), you can set the height of inner blocks in % . So, adding one inline-block with height: 100% in a block with fixed height would align another inline-block element in it ( <img/> in your case) vertically near it.
Answer: Use the CSS line-height property Suppose you have a div element with the height of 50px and you have placed some link inside the div that you want to align vertically center. The simplest way to do it is — just apply the line-height property with value equal to the height of div which is 50px .
How to Center a Div Vertically. To center a div vertically on a page, you can use the CSS position property, top property, and transform property. Start by setting the position of the div to absolute so that it's taken out of the normal document flow. Then set the top property to 50%.
You need to use JavaScript/jQuery to detect image height. CSS is not a dynamic language and you cannot detect height using pure css. Using jQuery you can do
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%;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With