Align html elements vertically with the browser size

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.