I have a custom script that is able to determine whether an image is in portrait or landscape orientation. Currently, the image is identified as being in landscape mode. My goal here is to crop and center the image using absolute positioning, specifying a height of 100% and applying a negative margin-left equal to half of the image's width.
Although I was successful in achieving the aforementioned tasks, I am currently facing a challenge. The images utilized in this scenario all have varying widths and heights since they are fetched from an API (specifically the Spotify API). As a result, I had to resort to JavaScript to accurately identify their respective widths. This process works perfectly fine until I apply the landscape
class. Essentially, what happens is that the script divides the image's width before it is resized to fit within the constraints of the 250px x 250px #container
div using the CSS properties assigned by that class.
My desired outcome is for the script to divide the image's width only after it has been successfully resized based on the attributes defined in 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');
}
});