JS implements an element with an unknown width that is centered vertically horizontally in the specified element:
This section describes how to implement an unknown width of the element to achieve vertical horizontal centering effect under the specified element, the following is a SPAN element as an example of how to implement the span element in the div to achieve horizontal vertical center effect, the code is as follows: <! DOCTYPE html>
<meta charset= "Utf-8" >
<meta name= "Author" content= "http://www.softwhy.com/"/>
<title> Ant Tribe </title>
<style type= "Text/css" >
#box {
width:200px;
height:150px;
Background:blue;
position:relative;
}
#antzone {
Background:green;
}
</style>
<script type= "Text/javascript" >
Window.onload=function () {
var Obox=document.getelementbyid ("box");
var Oantzone=document.getelementbyid ("Antzone");
var w=oantzone.offsetwidth;
var h=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>
<body>
<div id= "box" >
<spanj id= "Antzone" > Ant tribe </span>
</div>
</body>
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.
JS implements an element with an unknown width centered vertically horizontally in the specified element