[英]Vertically centering child div in parent container with JavaScript on page load is not setting position?
I am using JavaScript to vertically center a child div within a fluid container. 我正在使用JavaScript将一个子div垂直居中于一个流体容器中。 I essentially accomplish this by calculating the height of the parent container and the height of the child div. 我基本上通过计算父容器的高度和子div的高度来实现这一点。 I then absolutely positon the child div in the center of the parent div based on the height. 然后我绝对根据高度在父div的中心定位子div。 The issue I am experiencing is that when the page loads, it does not set the position of the child div. 我遇到的问题是,当页面加载时,它不会设置子div的位置。 I created a function out of this and call it when the window is resized so that when the viewport changes it recalculates dynamically. 我创建了一个函数,并在调整窗口大小时调用它,以便在视口更改时动态重新计算。 How would I go about initially setting this position on page load? 如何在页面加载时初始设置此位置?
<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();
});
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*/
}
<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);
return message.css('bottom', center);
};
$(function () {
$(window).resize(function () {
homepageLead();
}).resize();
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.