The table can display the vertical center of elements in td, But the precondition must be that the height of td is defined.
However, in many cases, elements are used to align vertically with the browser size, for example, when creating an official website or activity display network.
Problem:
Implement vertical center of div and remain centered when scaling the browser size.
Solution:
1. The height of the visible area of the browser-the height of the element/2 = the distance between the element and the top of the visible area of the browser.
(BodyHeight-divHeight)/2
2. If the visible area of the browser is smaller than the height of the element, the distance between the element and the top of the visible area of the browser is zero.
3. onresize () triggers an event when the browser size changes. Use onresize () to recalculate the distance from the element to the top of each 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);} |
Note:
The number of times the browser's onresize is triggered varies, so be careful when processing it.