Menü schliessen
Created: January 17th 2025
Last updated: January 30th 2025
Categories: Common Web Development,  IT Development
Author: Tim Fürer

CSS: How to Center a DIV

Tags:  CSS,  guide,  HTML
Donation Section: Background
Monero Badge: QR-Code
Monero Badge: Logo Icon Donate with Monero Badge: Logo Text
82uymVXLkvVbB4c4JpTd1tYm1yj1cKPKR2wqmw3XF8YXKTmY7JrTriP4pVwp2EJYBnCFdXhLq4zfFA6ic7VAWCFX5wfQbCC

Since the dawn of HTML and CSS, web developers have struggled with a certain, very basic task called, "Centring a DIV." The most effective solution to that challenge has evolved many times over the years. Here, I'll present two modern approaches for solving it.


Flexbox (The Backwards Compatible Way)

It feels weird to say, but Flexbox has been around for a good while now. Flexbox has made many previously difficult layouts trivial to re-produce. One of those layouts is the centred element, be it horizontal, vertical, or both.

To centre an element with Flexbox, follow these steps:

  • Apply "display: flex;" to the wrapper element.
  • Use "justify-content: center;" to horizontally centre the wrapper's child elements.
  • Use "align-items: center;" to vertically centre the wrapper's child elements.

Et voilà, that's all there is to it.


Align-Content (The Bleeding Edge Way)

In April of 2024, a new aspect of the align-content property became baseline available: its ability to vertically centre content for "display: block" elements. According to statistics on caniuse.com, over 89% of tracked browsers support this feature as of writing this article.

Usage is as simple as applying "align-content: center;" to any wrapper element.