Skip to main content

Vertical Centering

To center something vertically in CSS, reach for a modern layout technique such as Flexbox or Grid, or use positioning with transforms.


Center Align with Flexbox

A CSS flex container can center its elements horizontally as well as vertically.

The two properties to set on the container are justify-content and align-items. Give both the value center and the items are centered on each axis.

Example

Prompt
Center text both horizontally and vertically inside a container using flexbox. The container should have display: flex, justify-content: center, align-items: center, height 200px, and a 3px solid green border. Display "I am vertically and horizontally centered."
Output: complete HTML page

Center Align with Grid

A CSS Grid container can do the same, centering elements both ways.

Here one property is enough: with place-items set to center on the grid container, items are centered on each axis.

Example

Prompt
Center text both horizontally and vertically inside a container using CSS Grid. The container should have display: grid, place-items: center, height 200px, and a 3px solid green border. Display "I am vertically and horizontally centered."
Output: complete HTML page

Center Align with position and transform

When the element's dimensions are unknown or dynamic, combine position: absolute with transform: translate() to center it.

Example

Prompt
Center a paragraph both horizontally and vertically inside a container using position: absolute and transform: translate(-50%, -50%). The container should have a relative position, height 200px, and a 3px solid green border. The paragraph uses top: 50%, left: 50%, and transform: translate(-50%, -50%).
Output: complete HTML page