Friday, February 20, 2015

Center a div relative to viewport

Hi,

Here I will write some codes that will help center a div relative to the viewport. Let's begin with centering a div relative to viewport. The viewport is the display area for a web page on screen. Here you will find information about centering a div on the screen, i.e. center to the whole viewing window. 

DEMO

HTML Codes

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>How to ...</title>
  <style>
    #child {
     width:300px;
     height:300px;
     background:green;
     position:fixed;
     left:50%;
     top:50%;
     margin-left:-150px;
     margin-top:-150px;
    }

    #parent {
      display: block;
      position: absolute;
      width: 400px;
      height: 400px;
      background: red;
      bottom: 0;
      left: 0;
    }
   </style>
</head>
<body>
<div id="parent">
   I am parent div.
  <div id="child">Always center no matter where the Parent div is</div>
</div>
</body>
</html>

No comments:

Post a Comment