javascript - Centering div margin top and margin bottom -
i'm trying margin-top , margin-bottom center <div>
. javascript, wrote, works. however, if site cached once, ctrl+f5 refresh causes script receive wrong clientheight
. refreshing second time, retrieves correct clientheight
.
i've tried using window.load
, works. however, slow <div>
loads , after 2 seconds, shifts middle.
<script type="text/javascript"> var height = $(window).height(); var clientheight = document.getelementbyid('account-wall').clientheight; var calc_height = (height - clientheight) / 2; document.getelementbyid("account-wall").style.margintop = calc_height + 'px'; document.getelementbyid("account-wall").style.marginbottom = calc_height + 'px'; </script> <script type="text/javascript"> $(window).load(function() { var height = $(window).height(); console.log(height); var clientheight = $('.account-wall').height(); console.log(clientheight); var calc_height = (height - clientheight) / 2; document.getelementbyid("account-wall").style.margintop = calc_height + 'px'; document.getelementbyid("account-wall").style.marginbottom = calc_height + 'px'; }); </script>
use resize event since need centered if window.height changes. make sure centered beggining use .resize() trigger event.
$(window).on('resize', function(event){ var height = $(window).height(); console.log(height); var clientheight = $('.account-wall').height(); console.log(clientheight); var calc_height = (height - clientheight)/2; document.getelementbyid("account-wall").style.margintop = calc_height+'px'; document.getelementbyid("account-wall").style.marginbottom = calc_height+'px'; }).resize();
Comments
Post a Comment