Centering confuses everyone because context matters: inline text, block in parent, or unknown dimensions. These three recipes cover most UI work.
1. Text centering
text-align: center; on the parent—for inline content and text nodes.
2. Flex centering (favorite)
.center-flex {
display: flex;
justify-content: center;
align-items: center;
min-height: 8rem;
}
3. Grid centering
.center-grid {
display: grid;
place-items: center;
min-height: 8rem;
}
Practice
Switch the wrapper class between center-flex and center-grid in the playground.
Important interview questions and answers
- Q: How do you center a block horizontally with auto margins?
A: Set a width and `margin-left: auto; margin-right: auto;` on the block. - Q: Why is flex/grid centering popular?
A: It centers both axes without calculating positions, even with dynamic content size. - Q: Does `text-align: center` center divs?
A: No—it centers inline content inside the element, not block-level children.