Fill a div with a vertical centered image
using overflow hidden and jquery mobile function we are centering a floated image on a div container and positioning the image inside that div container
by heriberto perez
July 25, 2014
HTML
<body>
<div id='main-container'>
<div class="frame">
<img src="http://nosrc.net/1000" />
</div>
<div class="frame">
<img src="http://nosrc.net/1000" />
</div>
</div>
</body>
CSS
.frame {
width: 48%;
margin-right: 10px;
float: left;
height: 100%;
overflow: hidden;
position: relative;
}
.frame img {
width: 100%;
}
#main-container {
width: 100%;
background: yellow;
height: 500px;
}
JavaScript
$(function(){
centerImageVertically();
$(window).resize(function() {
centerImageVertically();
});
function centerImageVertically() {
var imgframes = $('.frame img');
imgframes.each(function(i){
var imgVRelativeOffset = ($(this).height() - $(this).parent().height()) / 2;
$(this).css({
'position': 'absolute',
'top': imgVRelativeOffset * -1
});
});
}
});