This Week I Learned: Centre a fixed div of changing width [2023–05–19]

Peter Brownlow
1 min readMay 19, 2023

--

Photo by Piret Ilver on Unsplash

It’s a smally but a goody.

I wanted to show a small message in my web app, perfectly centred, with dynamic content. It took me a while to figure it out, reading lots of CSS rules, but the solution is quite simple in the end.

The catch is that it’s on top of everything else, and it seemed that making it a fixed position is good for that, so normal display: flex tricks didn’t work for me. Worse, every time I changed the content to show a new message the right hand side would jump in and out.

I found various suggestions online but all relied on a fixed width, which I didn’t want because my messages vary in length quite a lot.

CSS:

.message {
text-align: center;
position: fixed;
z-index: 1;
}

JavaScript:

function showMessage(text) {
document.getElementById("id-of-your-p-element").innerText = text;
const messageContainer = document.getElementById("id-of-your-outer-div");
messageContainer.style.left =
`${(window.screen.width - messageContainer.offsetWidth) / 2}px`;
}

Very small, in the end.

--

--

Peter Brownlow

Software builder, people manager, topical deep-dive enthusiast