//css Way
<!DOCTYPE HTML><HTML><Head> <MetaCharSet= "Utf-8"> <title>CSS Position Positioning Implementation DIV in Window Center</title> <styletype= "Text/css">. Dialog{position:fixed;_position:Absolute;Z-index:1;Top:50%; Left:50%;margin:-141px 0 0-201px;width:400px;Height:280px;Border:1px solid #CCC;Line-height:280px;text-align:Center;font-size:14px;Background-color:#F4F4F4;Overflow:Hidden; } </style></Head><Bodystyle= "height:5000px;"> <Divclass= "Dialog">I am the CSS Center</Div></Body></HTML>
//js Way<!DOCTYPE HTML><HTML><Head> <MetaCharSet= "Utf-8"> <title>JQ DIV centered in window</title> <Scriptsrc= "Scripts/jquery-1.8.2.js"></Script> <styletype= "Text/css">. Dialog{position:Absolute;Z-index:1;width:400px;Border:1px solid #CCC;Line-height:280px;text-align:Center;font-size:14px;Background-color:#F4F4F4;Overflow:Hidden; } </style></Head><Bodystyle= "height:5000px;"> <Divclass= "Dialog">I am the JS Center</Div></Body></HTML><Script> $(function() {Loading ($ ('. Dialog')); $ (window). Scroll (function() {Loading ($ ('. Dialog')); }); $ (window). Resize (function() {Loading ($ ('. Dialog')); }); //Popup Center functionLoading ($obj) {//gets the width of the element itself varL1=$obj. Width (); //gets the height of the element itself varH1=$obj. Height (); //gets the left value of the actual page. (page width minus element self width/2) var Left=(Document.documentElement.clientWidth-L1)/ 2; //gets the top value of the actual page. (page width minus element self height/2) varTop=(Document.documentElement.clientHeight-H1)/ 2 +$ (document). ScrollTop (); $obj. css ({left:left+ 'px', Top:top+ 'px' }); } })</Script>
Div always centered, CSS and JS code