Flexbox:
.container {
display: flex;
justify-content: center;
align-items: center;
height: 300px;
}
Grid
.container {
display: grid;
place-items: center;
height: 300px;
}
Flex Margin
.container {
display: flex;
height: 300px;
}
.centered-div {
margin: auto;
}
Absolute Positioning
.container {
position: relative;
height: 300px;
}
.centered-div {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
Margin Auto
.container {
height: 300px;
}
.centered-div {
width: 200px;
margin: 0 auto;
position: relative;
top: 50%;
transform: translateY(-50%);
}
Grid Template
.container {
display: grid;
grid-template-columns: 1fr auto 1fr;
grid-template-rows: 1fr auto 1fr;
height: 300px;
}
.centered-div {
grid-column: 2;
grid-row: 2;
}
Top comments (1)
In my experience they height is not known and is defined by the child and that makes it a challenge to center.