HTML & CSS Interview Question #100
How can you center an element with modern CSS?
CSS Layout, Display, Positioning, Flexbox & Grid Mid-Level Intermediate
Quick Interview Answer
The best centering technique depends on the layout context. Flexbox can center along both axes with justify-content and align-items, while Grid can use place-items: center. Horizontal block centering can often use auto inline margins when a suitable width or max-width is defined.
Detailed Explanation
The best centering technique depends on the layout context. Flexbox can center along both axes with justify-content and align-items, while Grid can use place-items: center. Horizontal block centering can often use auto inline margins when a suitable width or max-width is defined.
Interview answers should avoid treating one centering trick as universal. First identify whether the requirement is inline text alignment, horizontal box centering, or two-axis layout alignment.
Code Example
.flex-center {
display: flex;
justify-content: center;
align-items: center;
min-height: 300px;
}
.grid-center {
display: grid;
place-items: center;
min-height: 300px;
}
.container {
max-width: 1200px;
margin-inline: auto;
}