CGPA Calculator Hash Generator Bcrypt Hasher Tree Visualizer Barcode Generator Engineering Blog Editorial Standards All Tools Games HTML5 JavaScript PHP MySQL

CSS Align

Centering elements is one of the most common tasks for a web designer. CSS provides various methods to align text and boxes horizontally or vertically.


Aligning Text

For text or inline elements inside a block, use the text-align property.

.container {
    text-align: center;
}

Centering Block Elements

To center a block element (like a <div>) horizontally, you must set its width (or max-width) and set margin: auto.

I am a centered div.
.center {
    margin: auto;
    width: 200px;
}

Centering Images

Images are inline elements by default. To center them like a block, you must set display: block and use margin: auto.

img {
    display: block;
    margin: 0 auto;
    width: 60%;
}

Vertical Centering

Centering an element vertically can be tricky. A common modern method is using absolute positioning combined with the transform property.

Perfectly Centered!
.parent { position: relative; height: 150px; }
.child {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}

Tip: While these methods are standard, modern developers now use Flexbox (justify-content: center; align-items: center;) for almost all centering tasks.