I'm facing a challenge when it comes to aligning images vertically inside divs.
The problem arises due to the following conditions:
- The images will have varying and unknown sizes.
- These images are larger than the divs they are contained in, requiring them to be masked by the divs.
- The website uses a responsive design approach, with media queries adjusting the layout for different screen sizes. This results in the sizes of the containing divs changing based on the screen size.
- On mobile devices like smartphones or tablets, the size of the containing div changes when the device is turned, without requiring a page refresh. The challenge here is to keep the image centered within the div under such circumstances.
I've encountered issues using display:table-cell
because the images exceed the div size, making it difficult to maintain proper height and apply overflow:hidden
.
I attempted to use jQuery vAlign, which works well unless there are changes in screen size (such as rotating a device). Since it's called on (document).ready
, the alignment does not update dynamically without a page refresh.
Is there a way to trigger vAlign using media queries? If not, is there a workaround for the table-cell method that allows smaller div
to mask larger img
with overflow:hidden
?
UPDATE: I've been experimenting with pure CSS (view the working example here) but still struggling to achieve the desired result.