I am facing an issue with a 240x240px div
that contains a fading slideshow of images of varying sizes. Each image is set to a height: 240px
, and the width adjusts proportionally to the height. For images that are taller than they are wide, I center them inside the div
using
position: relative; margin: 0 auto
. This method works well for most cases, but problem arises with images that overflow the 240px div
. How can I center these overflowing images inside the div
? I attempted a jQuery solution, but it doesn't seem to work as expected:
if( $("div img").width() > 240 ) {
$(this).css("margin-left", rv);
var rv = -1 * ($(this).width() / 4) + "px";
}
The idea behind this logic is that if the image extends beyond the width of the div
, then move it left by rv
px, where rv
is one-fourth of the image's width (to avoid clipping the image in half on the left side). My initial thought is that maybe referencing $(this)
is causing the issue, but I'm not entirely sure.
I understand that I could manually add inline CSS styles for individual images, but that approach is messy and time-consuming. I would prefer a script that can dynamically calculate the center of each image and adjust its position accordingly. Any suggestions?