Quick implementation
.center-in-the-viewport {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 100%;
max-width: 400px;
}Prompt this to your LLM
Includes role, constraints, two framework variants, and edge cases to handle.
You are a senior CSS developer. Create a centered overlay component using position: fixed and transform. Ensure it works on mobile. Provide two variants: one with a backdrop and one without. Handle edge cases where the content is larger than the viewport.
Example structure:
<div class="overlay">
<div class="content">...</div>
</div>
Constraints:
- Use oklch() for colors.
- Ensure z-index is managed correctly.
- Add focus trapping logic for accessibility.Why this matters in 2026
Centering elements reliably across browsers used to be a nightmare. This technique leverages modern transforms to achieve perfect centering without calculating offsets manually. It remains the standard for modals and overlays in 2026.
The logic
We position the element fixed to the viewport, then shift it 50% down and right. The negative translate moves it back by half its own width and height. This ensures the center point aligns exactly with the viewport center.
Accessibility & performance
Fixed positioning removes the element from the flow, so ensure focus management is handled via JavaScript. The transform property is GPU-accelerated, ensuring smooth rendering even on low-end devices. Always include a backdrop to prevent interaction with underlying content.