Skip to main content

Center position

How to center elements horizontally and vertically in CSS? Provide examples of different approaches​

Centering elements in CSS can be done in various ways, depending on whether you're centering inline elements, block elements, or using modern CSS techniques like Flexbox or Grid.

Horizontal centering with text-align:

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

Horizontal centering with margin: auto:

.centered-block {
width: 50%;
margin: 0 auto;
}

Vertical and horizontal centering with Flexbox:

Big O
.centered-flex {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}

Vertical and horizontal centering with Grid:

.centered-grid {
display: grid;
place-items: center;
height: 100vh;
}

Vertical centering with absolute positioning:

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