javascript - Centering DIV Horizontally & Vertically on Page Load -
how can center div both horizontally , vertically when page loads?
i using following solution:
html:
<div class="container"> <div class="visitorselect"> <a href="/visitorlog/boeing"> <div class="tile double icon bg-color-blue"> <div class="tile-content"> <i class="icon-plane"></i> </div> <div class="brand"> <span class="name">employee</span> </div> </div> </a> <a href="/visitorlog/guest"> <div class="tile double icon bg-color-orange"> <div class="tile-content"> <i class="icon-group"></i> </div> <div class="brand"> <span class="name">guest</span> </div> </div> </a> </div> <!-- visitorselect --> </div> <!-- container -->
javascript:
<script> $(document).ready(function() { $(window).resize(function() { $('.visitorselect').css( { position: 'absolute', left: ($(window).width() - $('.visitorselect').outerwidth()) / 2, top: ($(window).height() - $('.visitorselect').outerheight()) / 2 }); }); // call `resize` center elements $(window).resize(); }); </script>
when load page, div
center shows @ right of page , below center of vertical. however, when resize page manually snaps exactly should.
what additional steps need take cause centering place element @ time document loads?
set .visitor element absolute positioning before calculate width.
by default static divs stretch full width of parent; absolute divs not. messing first calculation.
you should set position css rule outside of resize event function, in either css or in ready() function. here's fix least changes code:
$(document).ready(function() { $(window).resize(function() { $('.visitorselect').css( { position: 'absolute' }); $('.visitorselect').css( { left: ($(window).width() - $('.visitorselect').outerwidth()) / 2, top: ($(window).height() - $('.visitorselect').outerheight()) / 2 }); }); // call `resize` center elements $(window).resize(); });
Comments
Post a Comment