JS implementation div centered example

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

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

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

text-align: center; 
<div id="main"> 
<div id="content"> 
<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; 


Related articles: