To display a div in browser window center we can use css position
value fixed
. The left and top value of fixed position are relative to visible window. Here is sample code and rendered screenshot for it.
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script> <style type="text/css" media="screen"> .center { position:fixed; background:green; width:200px; height:50px; left:50%; top:50%; margin-left:-100px; margin-top:-25px } </style> Hello world <div class="center">div in window center</div>
Few points to note
- We are using margin-left and margin-top negative value. mergin-left is negative half of div width and margin-top is negative half of div height.
-
Alternatively we can use left and top css property and use calc function as shown below:
left:calc(50% - 100px); top:calc(50% - 25px);
Note the space before and after minus (-). calc may not work in old IE browsers though.