javascript - Dynamically center div vertically and horizontally using jQuery -
i need center vertically , horizontally div called ".box" inside <body></body>. contains <h1>, , that's all. in future, may contents <img>.
i tried lot of tricks this, unfortunately doesn't work well...
so found on topic : centering div vertically & horizontally using jquery solution jquery. it's not working perfectly, because div stays on left of screen can see here : http://www.arcadmedia.com/
so i'm looking solution (in jquery, or in css nothing working me).
i think solutions 1 : http://jsfiddle.net/pqdqb/ not best, , jq can better.
i'm using code :
$(function() { $('.box').css({ 'position' : 'absolute', 'left' : '50%', 'top' : '50%', 'margin-left' : -$('.box').outerwidth()/2, 'margin-top' : -$('.box').outerheight()/2 }); }); i don't know problem.
edit : box has fit content dynamically!
this calculate dynamically , position .box @ center of screen. can call function on resize , rotate events.
$(updateboxdimension); $(window).on('resize', updateboxdimension); function updateboxdimension() { var $box = $('.box'); // center box var boxleft = ($(window).width()) / 2 - ($box.width() / 2), boxtop = ($(window).height()) / 2 - ($box.height() / 2); $box.css({ left: boxleft, top: boxtop }); }
Comments
Post a Comment