Check out this demo on jsBin
For this demonstration, we have utilized the text-align:center;
property for our element #gallery
and set the image height to 100%
.
Furthermore, using jQuery, we verify if the image width exceeds the gallery width upon loading with .load()
. If it does, we adjust the width and vertically center align the image using jQuery. For example:
CSS Styles:
#gallery{
position:relative;
margin:0 auto;
width:600px;
height:500px;
border:1px solid #aaa;
text-align:center;
}
#gallery img{
height:100%;
}
jQuery Script:
$('#gallery img').load(function(){
img = $(this);
imgW = img.width();
if(imgW > $('#gallery').width()){
img.css({width:'100%', height:'auto'});
img.css({marginTop: $('#gallery').height()/2 - $(this).height()/2 });
}
});
Experiment with different image widths/heights to observe their responsiveness.