I am currently working on making the header slideshow responsive. I encountered an issue where I couldn't use the CSS property background
with cover
. Instead, I need to utilize <img>
inside a div.
<div class="parent">
<img src="slide.jpg" alt="">
</div>
In my attempt to solve this problem, I wrote the following code:
var imageContainer = $('.header');
var headerHeight = $('header').outerHeight();
var headerWidth = $('header').outerWidth();
var imgHeight = 498;
var imgWidth = 1900;
imageContainer.find('img').each(function() {
var ratio = headerWidth / imgWidth;
var newWidth = imgWidth * ratio;
var newHeight = imgHeight * ratio;
if (newHeight < headerHeight) {
ratio = newHeight / imgHeight;
$(this).css({
'height' : headerHeight,
'margin-left': -(imgWidth * ratio / 2)
})
} else {
$(this).css({
'width' : newWidth,
'margin-left': -(newWidth/2)
})
}
})
To illustrate, let's consider a scenario where the parent block is 2500x400 and the image is 1900x1400. Alternatively, the parent block could be 400x400.
I am seeking the most effective solution for ensuring responsive images within the block.
Any suggestions would be greatly appreciated. Thank you.