How to center a div

Recently I was asked simple question:

How would you center a div?

Instead of a clear answer popping into my head, I initially just had questions. Is it the only child DOM element? Is the size fixed? Is content length variable? What should the overflow behavior be? And many more. It's a meme for a reason 🀷

It struck me how interesting this simple question actually was, and so I wanted to dive in. Here's my version of The Definitive Guide on How to Center a Div.

All linked demos are single page examples with unminified CSS and JS and so are easily explored & downloaded.

Centered with flex πŸ”—

The most maintainable & capable way to center HTML elements is using display: flex. Flex can center horizontally, vertically, and has other alignment methods available. It also works on multiple DOM elements at the same tree level.

/* Centers child div horizontally & vertically */
display: flex;
align-items: center;
justify-content: center;

✨ Demo with flex

Use flex, unless you have a reason not to.

Centered absolutely πŸ”—

Centering with position: absolute is cheating. It's quick and easy but breaks down in many situations. It won't work with multiple DOM elements at the same level in the DOM tree. It also behaves differently when an element higher in the DOM tree has position: relative set. But if you must, here's how to do it:

position: absolute;
top: 50%;
left: 50%; s
transform: translate(-50%, -50%);

✨ Demo with absolute

Positioning absolutely does work well in modal/popup types of usages, where:

  • It's the only element being shown.
  • It's reliably a direct child of the <body> tag.

This is how Angular Material's CDK (opens new window) Dialog works. It creates a "portal" at the top-level of the DOM tree, and any dialogs are inserted there to ensure correct positioning. The CDK portal happens mostly under the hood, so you can create and use dialogs in any component and not have to worry about references directly to DOM elements.


🚧 ⚠ Warning: the rest of the methods are not recommended, for obvious reasons.


Centered over cursor πŸ”—

Why worry about where to position the div? Just put it on the user's cursor. If it's in the wrong place, it's a user error. There are two ways to do this: base64-encode the content, or get the mouse position in JS and update the content's absolute position.

Base64-encoded cursor πŸ”—

Content can be saved as an image, then that image can be used as a CSS cursor.

cursor: url('my-cool.svg'), auto;

For our example, it seemed like cheating to screenshot content and format the image. Instead, the demo page draws the content in a <canvas> element and then the content is base64-encoded and logged to the console. From there, I copied the data and put it into css using cursor: url('data:image/jpeg;base64,LONG-DATA-STRING', auto);.

The most difficult part about getting this working was the browser silently disallowing images over a certain size. Eventually I figured out I needed to first size the canvas element to 128x128 pixels before base64-encoding the data. MDN has helpful details and best-practices (opens new window) to consider if this is a technique you need to implement.

✨ Demo with base64 cursor

Cursor position in JS πŸ”—

In addition to the pure-CSS approaches, you can let JavaScript assist a little to improve the flexibility. Listening to the mousemove event allows for tracking the mouse position, and in the event listener you can pass the values from JS to CSS variables.

window.addEventListener('mousemove', (event) => {
  const { pageX, pageY } = event;
  root.style.setProperty('--cursor-x', `${pageX}px`);
  root.style.setProperty('--cursor-y', `${pageY}px`);
});

In CSS the content can be positioned absolutely, with the left and top values coming from the CSS variables.

left: var(--cursor-x);
top: var(--cursor-y);

✨ Demo with cursor centering

Centered geospatially πŸ”—

If you're trying to center content on a web page, you're thinking too small. Instead, center it on ...the planet. Get a user's location using navigator.geolocation.getCurrentPosition(). Once the latitude and longitude coordinates are known, center the content over the user's location using Globe.gl (opens new window) to plot it on a globe.

✨ Demo with geo centering

Centered gyroscopically πŸ”—

This approach will only work on mobile devices, but it's a lot of fun. The deviceorientation (opens new window) event exposes a devices gryoscope & accelerometer data. To see all of what's possible, check out this very detailed demo (opens new window) on sensor data available in JS.

✨ Demo with gyroscopic centering

And if all else fails... πŸ”—

You can party like it's 1999 and do your whole layout in a <table>.

About Me

Hi, I'm Dominic πŸ‘‹ I'm a software engineer building front-end web apps, back-end services, and some things in between. I most enjoy working with TypeScript and .NET (6+/Core). Check out some of my projects, or get in touch.