I’m trying to center a block element (img or div) to a container which has a % width and height %.
Here’s what I did. http://jsbin.com/ibakuw
$('#container img')
.css({
'margin': ($('#container').height() - $('#container img').height()) / 2 + 'auto',
'background':'red'});
I don’t want to use this {position:absolute; top:50%; height:240px; margin-top:-120px; }
approach to center vertically because the elements overflows my browser or container. I just need it to be constraint within the browser.
Please help. thank You!
edited:
I added $(window).resize(function() { here http://jsbin.com/ibakuw/5
var contHeight = $('body').height(),
paddVertical = ($('#container').height() - $('#container img').height()) / 2,
paddHorizon = ($('#container').width() - $('#container img').width()) / 2;
$(function() {
$('#container img')
.css({
'marginLeft' : paddHorizon +'px',
'marginTop' : paddVertical +'px'
});
$(window).resize(function() {
$('#container img')
.css({
'marginLeft' : paddHorizon +'px',
'marginTop' : paddVertical +'px'
});
});
});
Check out my example here http://jsfiddle.net/z8gph/
Unless I have your exact setup this is the closest I can get to answering your question.
First position the outer and inner containers relative.
Using jquery to center vertically you get the height of the outer container minus the inner container and divide that by 2. Then set the top with
.cssof the inner container to the result.EDIT
check out my new example http://jsfiddle.net/z8gph/1/
If you want it to work without setting
margin: 0 auto;to help center horizontally see here http://jsfiddle.net/z8gph/2/