Skip to main content

CSS Centering Elements

CSS offers several centering methods, and the right one depends on the type of element. Elements can be centered horizontally, vertically, or in both directions.

Example

Flexbox centers this <div> element.

Prompt
Center a div element both horizontally and vertically inside a container using flexbox. The container should have a fixed height (e.g. 300px) and a border. The centered element should display "I am vertically and horizontally centered." Use justify-content: center and align-items: center.
Output: complete HTML page

Horizontal Alignment

Block elements can be centered with margin: auto, and text inside elements with text-align: center. For left or right alignment, there are float and position.


Vertical Alignment

Modern layout techniques handle vertical centering in several ways: align-items: center in flexbox, place-items: center in grid, and, when an element's dimensions are unknown, position combined with transform.

Tip: To center content in both directions, flexbox is the recommended and most modern choice.