The perfect solution for DIV Center

Source: Internet
Author: User
Tags window
To solve the current web refactoring, we typically do div centered:
body{
margin:0px Auto;
Text-align:center;
}
But the page will go wrong without stating the following parsing method. cannot be centered!
<! DOCTYPE HTML PUBLIC "-//w3c//dtd XHTML 1.1//en" "Http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd" >
It bothered me for a few days. So some friends will say: "You add this sentence is not the line?" But sometimes the page can not be all according to the rules of the code format to write, for example, to change the colorful scroll bar.
Until yesterday, an idea flashed in my mind. Why not use JS to control the margins of the page? Do what you say!
Got a page. Added the following small piece of code.
<script language= "javascript" type= "Text/javascript" src= "Function.js" ></script>
Function.js content:
if (window.screen.width>800) {document.write ("<style type=\" text/css\ ">body{margin-left:" + ( window.screen.width-800)/2+ "px}</style>");
Save, Test. Haha, a few different resolutions can be normal center! The experiment was successful.
To sum up:
The main thing is that this code works:
(window.screen.width-800)/2//Calculate the margin value that the page should leave out. 800 for my div width + scroll bar width. The actual application is changed to your own size.
Add a point: The above JS must be placed behind your last CSS connection or </style>.

Welcome everyone to my station to communicate a better way to achieve!

Related Article

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.