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.
For text or inline elements inside a block, use the text-align property.
.container {
text-align: center;
}
To center a block element (like a <div>) horizontally, you must set its width (or max-width) and set margin: auto.
.center {
margin: auto;
width: 200px;
}
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%;
}
Centering an element vertically can be tricky. A common modern method is using absolute positioning combined with the transform property.
.parent { position: relative; height: 150px; }
.child {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
justify-content: center; align-items: center;) for almost all centering tasks.