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 class="container">
  Content
</div>
CSS
.container {
  display: block;
  align-content: center;
  height: 100%;
}

This feature is supported by all modern browsers:

align-content support in different browsers

Flexbox

HTML
<div class="container">
  <div class="center-item">
    Content
  </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 class="container">
  <div class="center-item">
    Content
  </div>
</div>
CSS
.container {
  display: grid;
  place-items: center;
  height: 100%;
}

This method uses the CSS grid layout to center the child element vertically and horizontally within the parent container. The place-items property set to center aligns the child element both vertically and horizontally.

Table Cell

HTML
<div class="container">
  <div class="center-item">
    Content
  </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
<div class="container">
  <div class="center-item">
    Content
  </div>
</div>
CSS
.container {
  position: relative;
  height: 100%;
}
.center-item {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
}

This method uses CSS transforms to center the child element vertically within the parent container. The top: 50% property positions the child element vertically halfway down the parent container, and the transform: translateY(-50%) property moves the child element upwards by half its own height, effectively centering it vertically within the parent container.

Photo by Jon Tyson on Unsplash



Comments

Leave a Reply

Your email address will not be published. Required fields are marked *