Center Dot

HTML: how to vertically center an object with CSS?

By

in

There are several ways to vertically center an object with CSS:

align-content Property

Since Google I/O 2024, a new CSS solution to vertically align an object was shown by the Chrome Development Team. Inside a block element it’s now possible to use the align-content property. The alignment works without additional html blocks or CSS definitions and excludes the side effects when using a workaround like Flex or Grid layout.

The align-content property can now be applied directly to a block container:

HTML </div> </div>’ style=”color:#D4D4D4;display:none” aria-label=”Copy” class=”code-block-pro-copy-button”>
<div class="container">
  <div class="center-item">
    <!-- content goes here -->
  </div>
</div>
CSS
.container {
  display: flex;
  align-items: center;
  height: 100%;
}

This method uses the CSS flexbox layout to center the child element vertically within the parent container. The align-items property set to center aligns the child element along the cross axis.

Grid Layout

HTML </div> </div>’ style=”color:#D4D4D4;display:none” aria-label=”Copy” class=”code-block-pro-copy-button”>
<div class="container">
  <div class="center-item">
    <!-- content goes here -->
  </div>
</div>
CSS
.container {
  display: table-cell;
  vertical-align: middle;
  height: 100%;
}

This method uses the CSS table layout to center the child element vertically within the parent container. The display: table-cell and vertical-align: middle properties treat the parent container as a table cell and vertically center the child element within it.

Transforms

HTML