Div is centered in the browser window

Source: Internet
Author: User

Centers the div relative to the browser window.

<!DOCTYPE HTML><HTML><Head><MetaCharSet= "Utf-8"><title>Test file</title><style>#test{width:200px;Height:200px;Background-color:#FC0;position:fixed;}</style><Script>window.onload= function(){    varScreen_width=Window.screen.availWidth;//Get screen width    varScreen_height=Window.screen.availHeight;//Get screen height    varX=(Screen_width-  $)/2;    varY=(Screen_height-  $)/2;    varDiv=document.getElementById ("Test"); Div.style.left=X+ "px"; Div.style.top=Y+ "px";};</Script></Head><Body><DivID= "Test"></Div></Body></HTML>

Several key points are explained below:

Position:fixed determines that the div is centered relative to the browser window, not the parent window relative to the general sense.

You must use Window.onload to ensure that the defer property of the js,<script> tag is not executed until the DOM is loaded, but the defer attribute is only supported by IE browser, and I use it with no effect.

Div is centered in the browser window

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.