JS implements an element with an unknown width that is centered vertically horizontally in the specified element:
This section describes how to implement an element with unknown width to achieve vertical horizontal centering under a specified element, with the span element as an example of how to implement a SPAN element to achieve horizontal vertical centering in a Div, the code is as follows:
<!DOCTYPE HTML><HTML><Head><MetaCharSet= "Utf-8"><Metaname= "Author"content= "http://www.softwhy.com/" /><title>Ant Tribe</title><styletype= "Text/css">#box{width:200px;Height:150px;background:Blue;position:relative;}#antzone{background:Green;}</style><Scripttype= "Text/javascript">window.onload=function(){ varObox=document.getElementById ("Box"); varOantzone=document.getElementById ("Antzone"); varW=Oantzone.offsetwidth; varh=Oantzone.offsetheight; Oantzone.style.position="Absolute"; Oantzone.style.left="50%"; Oantzone.style.top="50%"; Oantzone.style.marginLeft=-(W/2) + "px";Oantzone.style.marginTop=-(H/2) + "px";}</Script></Head><Body><DivID= "box"> <SpanjID= "Antzone">Ant Tribe</span></Div></Body></HTML>
Above your code to achieve the span element in the DIV vertical horizontal Center effect, the following is a brief introduction of its implementation process.
I. Principle of implementation:
Although CSS gives the dimension of the span element explicitly, it has a size that can be obtained using the offsetwidth and Offsetheight properties, then set the span element to absolute positioning, and then set the left and top property values to 50% respectively , but this time not the center of the span element is centered vertically, but the top-left corner of the span element is centered vertically, then the negative margin of the span element is set, and the dimension is half the width of the span element, thus achieving a vertical horizontal centering effect.
Two. Related reading:
1.offsetWidth refer to the Offsetwidth property for a detailed section on attribute usage, such as scrolltop, Offsetheight, and offsettop.
The original address is: http://www.softwhy.com/forum.php?mod=viewthread&tid=14785
JS implements an element with an unknown width centered vertically horizontally in the specified element