Quick implementation
.container {
display: flex;
justify-content: center; /* Horizontal centering */
align-items: center; /* Vertical centering */
min-height: 12rem; /* Ensure container has height */
}
.child {
/* Content styles */
}Prompt this to your LLM
Includes role, constraints, two framework variants, and edge cases to handle.
Act as a senior CSS developer. Write a CSS snippet to center a child element both vertically and horizontally within a parent container.
Requirements:
1. Use Flexbox (display: flex).
2. The parent must have a defined height or min-height.
3. Use justify-content: center for horizontal alignment.
4. Use align-items: center for vertical alignment.
5. Provide a fallback for older browsers if necessary (though Flexbox is widely supported).
6. Include a responsive variant where the container adapts to content width if needed.
Output format:
- CSS code block.
- Brief explanation of properties used.
- HTML structure example.Why this matters in 2026
Despite the rise of CSS Grid, Flexbox remains the most efficient tool for one-dimensional centering. It is the standard solution for centering modals, cards, and hero content, offering better browser support and simpler syntax than older hacks like absolute positioning.
The logic
The parent container needs display: flex to activate the flex formatting context. justify-content: center aligns items along the main axis (usually horizontal), while align-items: center aligns them along the cross axis (usually vertical). Crucially, the parent must have a height defined (e.g., min-height: 100vh or 12rem) for vertical centering to be visible.
Accessibility & performance
This method is fully accessible and does not impact screen readers. It is performant as it relies on the compositor-friendly flexbox layout engine. Ensure the contrast between the centered content and the background meets WCAG standards.