JS implementation div centered example

  • 2020-03-30 02:41:27
  • OfStack

 
<!DOCTYPE html> 
<html> 
<head> 
<meta charset="utf-8" /> 
<title>JS implementation div In the middle </title> 
<style> 
 
#main { 
position: absolute;  
background-color: blue; 
width:400px; 
height:200px; 
 
border:1px solid #00F; 
} 

#content { 
position: absolute;  
background-color: yellow; 
width: 200px; 
height: 100px; 
 

 
text-align: center; 
line-height:100px;  
} 
</style> 
<body> 
<div id="main"> 
<div id="content"> 
Sun 
</div> 
</div> 
<script type="text/javascript"> 
window.onload = function() { 
//Get browser window
var windowScreen = document.documentElement; 
//Gets the div element of main
var main_div = document.getElementById("main"); 
//Calculate the position by the window width and div width
var main_left = (windowScreen.clientWidth - main_div.clientWidth)/2 + "px"; 
var main_top = (windowScreen.clientHeight - main_div.clientHeight)/2 + "px"; 
//Location assignment
main_div.style.left = main_left; 
main_div.style.top = main_top; 

//Gets the div element of McOntent
var content_div = document.getElementById("content"); 
var content_left = (main_div.clientWidth - content_div.clientWidth)/2 + "px"; 
var content_top = (main_div.clientHeight - content_div.clientHeight)/2 + "px"; 
content_div.style.left = content_left; 
content_div.style.top = content_top; 

} 
</script> 
</body> 
</html> 

Related articles: