Friday, February 20, 2015

Center a div relative to parent div

Hi,

In this post I will write some codes to help center a div relative to a parent div. This is unlike the my earlier post which centers the div relative to the viewport/window. Lets begin.


HTML Codes

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>How to ...</title>
  <style>
    #child {
     width:300px;
     height:300px;
     background:green;
     position:relative;
     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">Center within the parent div.</div>
</div>
</body>
</html>

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>