W3docs

How to Make the CSS vertical-align Property Work on the <div> Element

In this snippet, we’ll demonstrate how you can use the CSS vertical-align property with the “middle” value on the HTML <div> element. See some examples.

Solutions with the CSS display property

Vertically centering a <div> element within another <div> requires adjusting the display property, as the CSS vertical-align property only works on inline, inline-block, or table-cell elements.

In this snippet, we demonstrate two methods using the display property.

Example of vertically centering a <div> within another <div> using the “flex” value of the display property:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      .container {
        display: flex;
        align-items: center;
        background-color: #f8fc03;
        height: 200px;
      }
    </style>
  </head>
  <body>
    <div class="container">
      <div>Hello world!</div>
    </div>
  </body>
</html>

Result

<div class="demo px-2.5 mt-1 mb-5 not-prose"> XFI2 <div> Hello world! </div> XFI3 </div>

In the next example, we use the display property with the “table” value for the outer container and the “table-cell” value for the inner container.

Example of vertically centering a <div> within another <div> using the “table” value of the display property:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      .container {
        display: table;
        height: 200px;
      }
      .inner {
        display: table-cell;
        vertical-align: middle;
        background-color: #aef5b8;
      }
    </style>
  </head>
  <body>
    <div class="container">
      <div class="inner">Text</div>
    </div>
  </body>
</html>