How to display a div in browser window center

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.
div-position-fixed-window-center

<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>
refresh

Few points to note

  1. 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.
  2. 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.

Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments