How do I center a div both vertically and horizontally using CSS?

Question

Centering a div element both vertically and horizontally is a common requirement in web design, especially when creating landing pages, modals, or full-screen sections. There are multiple ways to achieve this depending on the layout context and desired compatibility.

The most modern and reliable method is to use Flexbox, but other options include Grid, absolute positioning, and even CSS transforms. This question covers the most effective and widely-supported techniques for centering elements in the viewport or within a parent container using pure CSS.

Leave an answer