I have a script setup that detects whether an image is portrait or landscape. In this case the image is landscape. What I want to do is crop and center the image using absolute positioning, setting the height to 100% and giving it a negative margin-left based on half the image's width.
I was able to do the above but here's the the problem I'm running into: The images I'm using all have variable widths/heights due to each of them being called from an API (in this case the Spotify API). That being said I had to use some Javascript to find their correct width. Its doing just that but only before I add the class landscape
, so in actuality its dividing the image width before being resized to fit in the 250px x 250px #container
div using the css from that class.
What I want it to do is divide the image's width after after its been resized using the properties from the landscape
class.
HTML
<div id="container">
<img src="https://i.scdn.co/image/9c4880556288e2f4d098a104f5125e477611be32" >
</div>
CSS
#container {height: 250px; width: 250px; overflow: hidden; position: relative;}
.landscape {position: absolute; height: 100%; left: 50%;}
.portrait {width: 100%;}
JS
$(function() {
var $img = $('img'),
$imgHeight = $img.height(),
$imgWidth = $img.width();
if ($imgWidth > $imgHeight) {
$img
.addClass('landscape')
.css({
marginLeft: '-' + $imgWidth / 2 + 'px',
});
} else {
$img.addClass('portrait');
}
});