I've integrated Nivo Slider into my responsive website to display an image gallery. The slider spans 100% width and adjusts its height based on the aspect ratio of the images (all images have the same height).
However, if the user's connection is slow or the images are large in size, the slider may take a while to load. During this loading time, the preloader icon isn't displayed because the slider has a height of 0. Once the slider finishes loading, the height abruptly changes to the correct value based on the images' height. This sudden change can be jarring, especially if other elements like titles or paragraphs have already loaded.
My objective is to set the final height for the Nivo Slider before the images finish loading. This would prevent the annoying "jump effect" and give users a visual cue with the preloader icon, indicating that content is still loading.
Predictable Aspect Ratio
If I know the aspect ratio of the images beforehand, I can adjust the Nivo Slider's CSS accordingly. Below is an example using a 2:1 aspect ratio:
HTML
<div class="theme-default">
<div class="nivoSlider">
<img src="img/one.jpg" />
<img src="img/two.jpg" />
</div>
</div>
CSS
.theme-default {
padding-top: 50%; /* aspect ratio 2:1 */
height:0;
position: relative;
}
.theme-default .nivoSlider {
position:absolute;
left:0;
top:0;
right:0;
bottom:0;
background:#fff url(loading.gif) no-repeat 50% 50%;
}
.theme-default .nivoSlider img {
position:absolute;
top:0px;
left:0px;
display:none;
height: 100% !important;
}
Unknown Aspect Ratio
But what if I don't know the exact aspect ratio of the images upfront (only certain they have the same height)? How can I anticipate their dimensions to compute the correct aspect ratio?