When we have the div centered, there are generally two methods, one is fixed to the left and right width, that is, the use of pixel absolute positioning, and the other is a percentage of relative positioning, in this two ways, absolute positioning is not allowed to adapt to the screen, and the percentage can be, but, There's a new problem with percentages, if there's a sentence on our page
<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
, the percentage of top will be invalidated, and the deletion of this sentence, all normal, is not aware of the standard statement why it brings such inconvenience
To solve this problem, I use the following method to implement the Div adaptive
First of all, I use the absolute positioning of the way, first set a good div left and right up the bottom margin. Add two events to the body.
<body bgcolor= "#666666" onresize= "Test ()" onload= "Getwah ()" >
Getwah () is used to get the size of the screen and the various margins of the Div, and to calculate their difference
Copy Code code as follows:
var height,width,width_cha1,width_cha2;
function Getwah ()
{
if (document.documentelement && document.documentElement.clientWidth)
{d_width = Document.documentElement.clientWidth;}
else if (document.body)
{d_width = Document.body.clientWidth;}
Width=parseint (D_width);
Width_cha1=width-parseint (document.getElementById ("Backi"). Style.left)
Width_cha2=width-parseint (document.getElementById ("Massage_box"). Style.left)
}
When the screen size changes (onresize) triggers the test () function, which is the user based on the difference between the screen and the margin to reset the div's margin, so that you can achieve the size of the party screen changes, the DIV's margin will also change accordingly, So that the div can be adapted as the screen size changes
Copy Code code as follows:
Function test ()
{
if (document.documentelement && document). Documentelement.clientwidth)
{d_width = document.documentElement.clientWidth;}
Else if (document.body)
{d_width = document.body.clientWidth;}
var now_left1=parseint (d_width)-width_cha1;
var now_left2=parseint (d_width)-width_cha2;
document.getElementById ("Backi"). STYLE.LEFT=NOW_LEFT1
document.getElementById ("Massage_box"). Style.left =NOW_LEFT2
}