Does the vertically centering child div in the parent container with JavaScript on the page load not set the position?

I use JavaScript to vertically center the child div in a fluid container. I essentially accomplish this by calculating the height of the parent container and the height of the child div. I then absolutely put the child div in the center of the parent div based on height. The problem I'm experiencing is that when the page loads, it does not set the position of the child div. I created a function from this and call it when the window size changes, so that when the viewport changes, it dynamically recounts. How will I first set this position when loading the page?

<div class="lead"> <div class="message"></div> </div> var homepageLead = function () { var lead = $('.lead'), message = $('.message'), lead_height = lead.height(), message_height = message.height(), lead_center = .5 * lead_height, message_center = .5 * message_height, center = (lead_center - message_center); message.css('bottom',center); } homepageLead(); $(window).resize(function () { homepageLead(); }); 
+4
source share
1 answer

Try this script: http://jsfiddle.net/nRRn6/

used css:

 html, body { height:100%; } .lead { width:100%; height:100%; background:red; position:relative; } .message { width:120px; height:200px; background:yellow; position:absolute; /* <---required*/ left:0; /* <---required*/ bottom:0; /* <---required*/ } 

used html:

 <div class="lead"> <div class="message"></div> </div> 

jQuery used:

 var homepageLead = function () { var lead = $('.lead'), message = $('.message'), lead_height = lead.height(), message_height = message.height(), lead_center = .5 * lead_height, message_center = .5 * message_height, center = (lead_center - message_center); return message.css('bottom', center); }; $(function () { $(window).resize(function () { homepageLead(); }).resize(); }); 
+3
source

All Articles