SmartCodingTips

Centering Elements in CSS

Centering content in CSS can be done in multiple ways depending on the context — whether you're centering text, inline elements, block elements, or entire containers.

1. Centering Text

Use text-align: center; on the parent container:


.center-text {
    text-align: center;
}
            

2. Horizontally Center a Block Element

Use margin: 0 auto; and set a width:


.center-block {
    width: 300px;
    margin: 0 auto;
}
            

3. Centering with Flexbox

Flexbox makes it easy to center content both horizontally and vertically:


.flex-center {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 300px;
}
            

4. Centering with CSS Grid

CSS Grid allows centering using place-items:


.grid-center {
    display: grid;
    place-items: center;
    height: 300px;
}
            

5. Center with Absolute Positioning

Using transforms is another method to center an element:


.absolute-center {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}
            

Conclusion

Centering elements in CSS depends on the context. Use text-align for inline content, margin: auto for block elements, and modern layout techniques like Flexbox or Grid for complete control.