The table can realize the vertical center of the elements in TD, but the prerequisite must define TD's higher feasible.
But many times use the element to follow the size of the browser vertically centered, such as in the production of display official website, activity Display network and so on.
Problem:
The implementation div is centered vertically and is still centered when zooming the browser size.
Solution:
1, the height of the browser visual area-the height of the element/2 = the distance from the top of the viewable area of the browser.
(bodyheight–divheight)/2
2, the browser viewable area if less than the height of the element, that is, the element distance from the top of the browser viewable area is zero.
3. OnResize () triggers events when the size of the browser changes. Use OnResize () to recalculate the distance to the top of the element each time you change.
Implementation code:
function Divmiddle () {
var dairybox = document.getElementById (' Dairybox ');
var divheight = dairybox.offsetheight;
var bodyheight = document.body.offsetHeight;
if (Bodyheight > Divheight) {
var endheight = parseint (bodyheight-divheight)/2;
DairyBox.style.marginTop = endheight + "px";
} else{
dairyBox.style.marginTop = 0;
dairyBox.style.top = 0;
}
}
if (document.all) {
window.attachevent (' onload ', divmiddle);
} else{
window.addeventlistener (' Load ', divmiddle,false);
}
var resizetimer = null;
Window.onresize = function () {
Resizetimer = resizetimer?null:settimeout (divmiddle,0);
}
Precautions:
Depending on the different onresize of the browser, the number of times triggered is not the same, so be careful when dealing with them.
The above is a small series for everyone to bring HTML elements with the size of the browser to adapt the vertical center of the implementation of the whole content, I hope that we support the cloud Habitat Community ~