To allow HTML elements to fit into the browser's size adaptive vertical Center implementation _javascript Tips

Source: Internet
Author: User

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 ~

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.