Skip to main content

Horizontal Centering

CSS offers several ways of centering things horizontally, and the type of element decides which one fits.


Center Align Block Elements

A block-level element like a <div> is centered with margin: auto, provided it has a width. Without one, the element stretches to fill its container.

Note: When width is missing or set to 100%, center aligning does nothing on block-level elements.

Example

Here a <div> element with a width of 50% sits in the center.

Prompt
Center a div element horizontally using margin: auto. The div should have width 50%, a 3px solid green border, and 10px padding. Include the text "This div element is centered."
Output: complete HTML page

Center Align Text

Text inside a block-level element is centered with text-align: center.

Example

Prompt
Center the text inside a paragraph element using text-align: center. The paragraph should display "This text is centered."
Output: complete HTML page

Center Align an Image

An image needs two steps to be centered: turn it into a block element with display: block, then set both margin-left and margin-right to auto.

Example

Prompt
Center an image horizontally by setting display: block and margin-left/margin-right to auto. The image should have width 40%. Use any placeholder image.
Output: complete HTML page

Left and Right Align - Using position

Setting position: absolute is one way to align elements to the left or right.

Note: Elements positioned this way leave the normal flow and may overlap other elements.

Example

Prompt
Align a div to the right using position: absolute and right: 0px. The div should have width 300px, a 3px solid green border, and 10px padding.
Output: complete HTML page

Left and Right Align - Using float

The float property offers a different way to align an element to the left or right.

Example

Prompt
Align a div to the right using float: right. The div should have width 300px, a 3px solid green border, and 10px padding.
Output: complete HTML page