When we center a DIV, there are generally two methods, one is to fix the left and right width, that is, to use absolute pixel positioning; the other is to use relative percentage positioning, in either of these ways, absolute positioning does not allow the DIV to adapt to the screen, but the percentage can be used. However, a new problem arises when the percentage is used, if there is such a sentence in our page
<! Doctype HTML public "-// W3C // dtd xhtml 1.0 transitional // en" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
When this statement is deleted, the percentage of the top statement will expire. However, when this statement is deleted, everything is normal and it is not clear why the standard statement is so inconvenient.
To solve this problem, I use the following method to implement Div adaptive
First, I use the absolute positioning method. First, set the left and right margins of the div. Add two events to the body,
<Body bgcolor = "#666666" onresize = "test ()" onLoad = "getwah ()">
Getwah () is used to obtain the screen size and each margin of the DIV, and calculate their difference.
CopyCode The Code is as follows: var height, width, width_cha1, width_cha2;
Function getwah ()
{
If(document.doc umentelement & document.doc umentelement. clientwidth)
{D_width = document.doc umentelement. 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), the test () function is triggered. This function is used to reset the margin of the DIV based on the difference between the screen and the margin obtained previously, in this way, the margin of the DIV is also changed after the screen size of the party is changed, so that the DIV can be adaptive with the size of the screen copy Code the code is as follows: function test ()
{< br> if(document.doc umentelement & document.doc umentelement. clientwidth)
{d_width = document.doc umentelement. clientwidth ;}< br> else if (document. body)
{d_width = document. body. clientwidth ;}< br> 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
}