Home > Web Front-end > JS Tutorial > Pure js code enables elements with unknown width and height to be displayed vertically, horizontally and centered in the specified element_javascript skills

Pure js code enables elements with unknown width and height to be displayed vertically, horizontally and centered in the specified element_javascript skills

WBOY
Release: 2016-05-16 15:39:43
Original
1365 people have browsed it

The following uses the span element as an example to introduce how to realize the horizontal and vertical centering effect of the span element in the div . The code is as follows:

<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>脚本之家</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>
</head>
<body>
<div id="box">
 <spanj id="antzone">脚本之家</span>
</div>
</body>
</html>
Copy after login

Your code above achieves the effect of vertically and horizontally centering the span element in the div. Here is a brief introduction to its implementation process.

1. Implementation principle:

Although CSS does not explicitly give the size of the span element, it does have a size after all. This size can be obtained using the offsetWidth and offsetHeight attributes, and then set the span element to absolute positioning, and then set the left and top attribute values. Set them to 50% respectively, but this time it is not the center point of the span element that is centered vertically and horizontally, but the upper left corner of the span element that is centered vertically and horizontally. Then the negative margin of the span element is set, and the size is half the width and height of the span element. , thus achieving the vertical and horizontal centering effect.

The above is the entire content of this article. That’s it for today. I will update you with details on the usage of attributes such as scrollTop, offsetHeight and offsetTop in the future. Please continue to pay attention to this site, thank you.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template