While this might appear to be a simple question, it has been troubling me for some time now.
Let me elaborate on what I am trying to accomplish.
I have a collection of images in a gallery, and my goal is to center each image vertically within its container. These images come in different shapes, sizes, and aspect ratios, making it necessary for my code to be adaptable for each image. Here is the current state of my code:
<div id="cbp-fwslider" class="cbp-fwslider">
<img src="images/large/1.jpg" alt="img01"/>
<img src="images/large/2.jpg" alt="img02"/>
<img src="images/large/3.jpg" alt="img03"/>
</div>
Below is my JavaScript:
var $img = $('div#cbp-fwslider img');
var ih = $img.height();
var $div = $('div#cbp-fwslider');
var dh = $div.height();
if (dh > ih) {
var dif = (dh - ih);
$img.css('margin-top', + dif / 2 + "px");
}
Although this method works to an extent, it calculates the correct "margin-top" value to vertically center the first image within the container and then applies it to all the images. This likely happens because I've instructed the JavaScript to set the same "margin-top" value for all images.
My query is, how can I create a variable that allows me to apply this separately to each item added to my gallery?
I apologize if this seems like a basic question that could have been answered elsewhere; I'm still quite new to JavaScript.
If anyone knows of a simpler or more effective way to achieve my objective, I would appreciate any guidance in the right direction.
It's important to note that both the container and the images have dynamic heights. Due to the gallery's functionality, I cannot use absolute positioning, and the technique mentioned HERE doesn't seem to work either.
Thank you in advance for any assistance.