Skip to content

CSS vertical-align div | Example for all browsers

  • by

CSS vertical align div

Here is example code of How to vertically center <div> inside the parent element with CSS:-

The best approach in modern browsers is to use flexbox, for other or older browsers you’ll need to implement a fallback solution.

<!DOCTYPE html>
<html>
<head>
    <style type="text/css">
        #div1 {
            height: 500px;
            padding: 5px;
            border: 2px solid red;
            display: flex;
            align-items: center; /* align vertical */
        }
    </style>

</head>
<body>


  <div id="div1">
    <div>
    Hello World!</div>
</div>


</body>
</html>

Output:

CSS vertical align div example

How to vertically center a div for all browsers?

Below is the best all-around solution to work vertically and horizontally center a fixed-width, flexible height content box. It was working for recent versions of Firefox, Opera, Chrome, and Safari.

<!DOCTYPE html>
<html>
<head>
    <style type="text/css">
        .outer {
          display: table;
          position: absolute;
          top: 0;
          left: 0;
          height: 100%;
          width: 100%;
          border: 1px solid red;
      }

      .middle {
          display: table-cell;
          vertical-align: middle;
          border: 1px solid green;
      }

      .inner {
          margin-left: auto;
          margin-right: auto;
          width: 400px;
          border: 1px solid blue;
          /*whatever width you want*/
      }
  </style>

</head>
<body>


   <div class="outer">
      <div class="middle">
        <div class="inner">
          <h1>The Content</h1>
          <p>Once upon a midnight dreary...</p>
      </div>
  </div>
</div>


</body>
</html>

Output:

vertically center a div for all browsers

Source: stackoverflow.com

Do comment if you have doubts and suggestions ono this tutorial.

Note: The All HTML Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading