Search code examples
javascriptcsscentering

How to vertically and horizontally align a div into center of page


I have read a quite a few tips on how to center an element or div on a page, but none of which seem to work. I've even made a JSFiddle to try it out:

http://jsfiddle.net/aLye7/

I'm sure it must be an easy answer, but I cant figure it out. Any help would be much appreciated.

<body>
  <div class="intro-area">
    <div class="intro-text">
      <p>This is a paragraph I want to center on the page.</p>
      <p>This is another paragraph I want to center on the page.</p>
    </div>
  </div>
</body>

.intro-area {
  background-color: #e7e7e7;
  display: table;
  text-align: center;
}

.intro-text {
  display: table-cell;
  vertical-align: middle;
}

Also, in the JSFiddle I'm dynamically pulling the height of the .intro-area div through the window.height function in javascript. That's how it's being used in my project.


Solution

  • For this specific case, add the following to force the html, body, and containing div to a height of 100%:

    html, body, .intro-area {
        height: 100%;
    }
    

    And the following to remove the default padding and margin from html and body:

    html, body {
        margin: 0;
        padding: 0;
    }
    

    No JavaScript necessary using this method.

    DEMO