When centering an element with CSS both vertically and horizontally relative to its parent container, there are various ways to achieve this. Choosing one method over another depends on the specific goal, as all approaches are valid and correct depending on the context.
For the document structure, we need a container element that will include the centered elements.
HTML
CSS
Using Grid Layout
.contenedor {
display: grid;
}
.elemento {
align-self: center;
justify-self: center;
}
Using Flex Layout
Option 1
This is my preferred option since it doesn’t require direct reference to the contained elements. We only need to specify how the parent container should handle its children.
.contenedor {
display: flex;
justify-content: center;
align-items: center;
}
- Option 2
.contenedor {
display: flex;
}
.elemento {
margin: auto;
}
Using Positioning
Some people consider this a “dirty” or outdated option for this task, but it’s still useful when working with layered positioning.
.contenedor {
position: relative;
}
.elemento {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}