jQuery - resizing image to fit div [duplicate] - javascript

This question already has answers here:
Resize an image to fit in div
(5 answers)
Closed 9 years ago.
I have divs varying in height and width and wish for my images to be automatically resized to fill these divs 100%, and then of course centred.
At the moment my images are set to width 100% and then using the jQuery below centred, but this only works for images where the height are more than the div once resized.. how would I make it 100% for both height and width and center also.. completely filling the div (even if this means stretching the image)!
Thanks.
$('img.shelf-img').each(function(i, item) {
var img_height = $(item).height();
var top_margin = -(img_height / 2);
$(item).css({
'top': '50%',
'margin-top': top_margin
});
});

Use CSS to set both the Width and Height of the image to 100% and the image will be automatically stretched to fill the containing div, without the need for jquery.
Also, you will not need to center the image as it will already be stretched to fill the div (centered with zero margins).
HTML:
<div id="containingDiv">
<img src="">
</div>
CSS:
#containingDiv{
width: 200px;
height: 100px;
}
#containingDiv img{
width: 100%;
height: 100%;
}
That way, if your users have javascript disabled, the image will still be stretched to fill the entire div width/height.
OR
The JQuery way (SHRINK/STRETCH TO FIT - INCLUDES WHITESPACE):
$('img.shelf-img').each(function(i, item) {
var img_height = $(item).height();
var div_height = $(item).parent().height();
if(img_height<div_height){
//IMAGE IS SHORTER THAN CONTAINER HEIGHT - CENTER IT VERTICALLY
var newMargin = (div_height-img_height)/2+'px';
$(item).css({'margin-top': newMargin });
}else if(img_height>div_height){
//IMAGE IS GREATER THAN CONTAINER HEIGHT - REDUCE HEIGHT TO CONTAINER MAX - SET WIDTH TO AUTO
$(item).css({'width': 'auto', 'height': '100%'});
//CENTER IT HORIZONTALLY
var img_width = $(item).width();
var div_width = $(item).parent().width();
var newMargin = (div_width-img_width)/2+'px';
$(item).css({'margin-left': newMargin});
}
});
The JQuery way - CROP TO FIT (NO WHITESPACE):
$('img.shelf-img').each(function(i, item) {
var img_height = $(item).height();
var div_height = $(item).parent().height();
if(img_height<div_height){
//INCREASE HEIGHT OF IMAGE TO MATCH CONTAINER
$(item).css({'width': 'auto', 'height': div_height });
//GET THE NEW WIDTH AFTER RESIZE
var img_width = $(item).width();
//GET THE PARENT WIDTH
var div_width = $(item).parent().width();
//GET THE NEW HORIZONTAL MARGIN
var newMargin = (div_width-img_width)/2+'px';
//SET THE NEW HORIZONTAL MARGIN (EXCESS IMAGE WIDTH IS CROPPED)
$(item).css({'margin-left': newMargin });
}else{
//CENTER IT VERTICALLY (EXCESS IMAGE HEIGHT IS CROPPED)
var newMargin = (div_height-img_height)/2+'px';
$(item).css({'margin-top': newMargin});
}
});

If you want to keep the image ratio, I would set max-height and max-width to 100%. Here's a sample to show how that works. That will effectively shrink images that are larger than the div, but it will keep the aspect ratio.
For images that are smaller than the div, you will have to scale up with JavaScript. The basic algorithm is like so:
Find the aspect ratio of the image (width / height)
Find the aspect ratio of the div (width / height)
If the image's aspect ratio is less than the div's, set the image's height to 100%
If the image's aspect ratio is greater than the div's, set the image's width to 100%
Whichever dimension is not set, set it to auto
Obviously, you could use this algorithm for scaling up or down, but if you can be guaranteed that your div will always be smaller than your image, you can use the simpler CSS solution.
It looks like you've got code to do centering, so I'll leave that to you.

Related

jQuery outerHeight() & height change flicker/fail on window resize to odd pixels

I have two side-by-side elements on a page. One elements has a fixed size (100vh) – .hero-half – and the other is fluid with text of varying lengths – .project-details. When the fluid text container extends to be taller than the image container, I want to apply a class to it that restricts the height of one of its child elements to bing the total text container height back to equal with the image height.
HTML:
<div class="project-details left">
<h1 class="project">Title</h1>
<div class="project-summary">
<div class="summary-container">
<p>A bunch of paragraphs here</p>
</div>
<a class="more" href="#">More</a>
<a class="less" href="#">Less</a>
</div>
</div>
<div class="hero hero-half right" style="background-image: url('/img/placeholder-vert1.jpg')"></div>
The relevant CSS:
.hero-half {
width: 50%;
height: 100vh;
}
.project-details {
width: 50%;
height: auto;
}
.project-summary .summary-container {
overflow: hidden;
&.restrict-height {
.summary-container {
// set max height
max-height: calc(100vh - 615px);
}
}
}
Here is my JS code:
$(function () {
var bpTab = 1024;
resize = function() {
var winWidth = $(window).width();
var heroHeight = $(".hero-half").outerHeight();
var boxHeight = $(".project-details").outerHeight();
var $box = $(".project-summary");
if ( boxHeight > heroHeight && winWidth > bpTab) {
// if on desktop layout AND if text is pusing box too big, restrict box height
$box.addClass("restrict-height");
} else {
// if not on desktop or text is not pushing box too big
$box.removeClass("restrict-height");
$box.removeClass("is-expanded");
};
};
// resize on window resize
$(window).bind("resize orientationchange", function(){
resize();
});
// resize on page load
resize();
});
So when the project-details div reaches a height taller than .hero-half, it adds a class that sets a max-height on one of the children, which brings the total height of .project-details back to equal or less than .hero-half.
However when I resize my window to force the the text to push the project-details height too tall and trigger the restrict-height class, it only works when the screen width and height add up to even numbers (either both width and height are even, or both odd). If it's an odd total the outerHeight of project-details seems to calculate incorrectly.
The problem, I think, is that the outerHeight of .project-details is sometimes being calculated at it's natural height before the text height it restricted, and sometimes it's being calculates after that class is applied and after the text height it restricted, which therefor decreases the .project-details height back into an acceptable range.
I've tried adding a timeout delay for the addition of the class hoping that the extra time would mean the outerHeight calculation was always correct, but it didn't make a difference.
How should I alter this JS code to make sure the .project-details outerHeight is always reading the height before the restrict-height class is applied?
And related: why would the odd pixel dimensions have any effect here?
The solution was at add a reset before the if/else loop to standardise the div height be removing the extra classes that may alter its height first.
var $box = $(".project-summary");
// reset
$box.removeClass("restrict-height");
$box.removeClass("is-expanded");
var winWidth = $(window).width();
var heroHeight = $(".hero-half").outerHeight();
var boxHeight = $(".project-details").outerHeight();

Responsive height for div element

I have this code for a responsive banner
.mybanner {
height:320px;
background:url(../img/banner.png) no-repeat;
background-size:100%;
}
responsive image background works fine, the only problem is .mybanner container's height is not changing
for example when i test with big screen
mybanner div element width = 980px
mybanner div element height = 320px
bakcground_image width = 980px
background_image height = 320px
but when i resized screen, let say width mybanner div element become 680px
mybanner div element width = 680px
mybanner div element height = 320px
bakcground_image width = 680px
background_image height = 220px
from that example there is different value mybannder height with background_image height, so it's become ugly white space
I already tried to modify it like this, to make .mybanner height became auto
.mybanner {
min-height:170px;
max-height:320px;
background:url(../img/banner.png) no-repeat;
background-size:100%;
}
or this:
.mybanner {
height:100%;
//height:auto;
background:url(../img/banner.png) no-repeat;
background-size:100%;
}
but not work....
any idea how to make height of div .mybanner change too depending on image size on his background
You can use javascript to change height.
<body onresize="resizediv()">
<div class="mybanner" id="mybanner">
...
<script>
function resizediv() {
div = document.getElementById('mybanner');
var imageSrc = div.style.backgroundImage.replace(/url\((['"])?(.*?)\1\)/gi, '$2').split(',')[0];
var image = new Image();
image.src = imageSrc;
var width = image.width,
height = image.height;
div.style.height = image.height;
}
</script>
Or There are all background size valid properties, you can chose best one:
http://www.w3schools.com/cssref/playit.asp?filename=playcss_background-size&preval=contain
Or simple don't use background, put the IMG to the div as a object and set image width 100% don't edit div and image height, it will compute automatically.

element.height returns visible height - I want total?

So apparently this is only happening to me - and I can't think why but if it works, I'm happy :)
I have a full screen slideshow and I have created a function that will vertically center any images that are too large.
function fixImages(){
maxheight = $('.index-slide-container').height();
$('.index-slide-container img').each( function(index, ele){
if (ele.height > maxheight){
offset = ( maxheight - ele.height ) / 2;
$(ele).css('top', offset + 'px');
}
});
}
fixImages();
However, ele.height returns the height of the visible part of the image (the height of it's container, as it has overflow:hidden, even though when I console.log(ele) and expand the element, 'height' is clearly the correct value.
I have also tried $(ele).height(), $(ele).css('height'), $(ele).outerHeight() and ele.clientHeight; all of which return the same.
Thanks
I made some tests, and $('img').height(); is giving me the right height of the picture.
If you wish to center the picture vertically why don't you use the absolute positioning with css like this for example :
.index-slide-container img {
position:absolute;
top:50%;
}
And than, you could set the negative margin programmatically with jQuery :
$('.index-slide-container img').each( function(i, e){
var height = $(e).height() / 2;
$(e).css({'margin-top':'-'+height});
});

Render images at a standard size without stretching, with a minimum size

I need to render profile images in a grid of exactly 101x155 each.
Some images are too small, some too big, most are not the right aspect ratio.
How do I show the img with a minimum width and height, no distortion, and show the exact size I want?
Without actually modifying the images, you have a few options available to you.
img { max-width: 101px max-height: 155px }
this will make sure that the images don't go above the 101x155px wide. Because they aren't the perfect aspect ratio there still will be whitespace on the sides of the image if the aspect ratio isn't perfect.
Another way would be to encase them in a container
<div><img .../></div>
div {width: 101px; height: 155px; overflow: hidden}
img {width: 101px;} /*or do height: 155px)*/
This isn't perfect but it gives you a different result. This will require the images to be either taller or wider for all images.
The best way would be to resize, but I know we can't always have our way :)
How about some jQuery? If you just include the <img> with class="grid-img":
$(".grid-img").each(function(i){
var width = $(this).width();
var height = $(this).height();
var ar = height/width;
if(width > 101) {
var newWidth = 101;
var newHeight = 101 * ar;
} else {
var newHeight = 155;
var newWidth = ar / newHeight;
}
$(this).height(newHeight);
$(this).width(newWidth);
});
what this should do is: if the image's width is too big, resize it based on the width (maintaining aspect ratio). if not, resize it based on height (again maintaining AR).

Dynamic Image Resizing

I have an image on a webpage that needs to be stretched to fit the available space in the window whilst maintaining its proportion. Here's what I've got:
http://www.lammypictures.com/test/
I would like the large image to proportionally stretch to match the height and widths of the browser, minus the size of the divs to the left and bottom.
So the problem is 2 fold really; first i need to get the max height and width minus the link and image bars, secondly i need to resize the image on a browser resize whilst maintaining proportions.
Any help would be much appreciated.
Cheers
CIP
You could try using jQuery ui scaling effect:
$(document).ready(function () {
resizeImage(); // initialize
$(window).resize(function () {
resizeImage(); // initialize again when the window changes
});
function resizeImage() {
var windowHeight = $(window).height() - $('#nav').height(),
windowWidth = $(window).width(),
percentage = 0;
if (windowHeight >= windowWidth) {
percentage = (windowWidth / $('#image').width() ) * 100;
}
else {
percentage = ( windowHeight / $('#image').height() ) * 100;
}
$('#image').effect('scale', { percent : percentage }, 1);
};
});
Tested and works great, however, a few tweaks maybe needed to get it just the way you like it.
You may just not setup the image element width and height attributes, and write next styles:
.hentry img { max-width: 100%; }
And it will shrink relative to the minimum side.
P.S. But not in position: absolute; block which not have any size. Set up the parent block to relative positioning.

Categories

Resources