CSS horizontal centering of a fixed div?

matt picture matt · Jul 1, 2010 · Viewed 163.9k times · Source
#menu {
    position: fixed;
    width: 800px;
    background: rgb(255, 255, 255); /* The Fallback */
    background: rgba(255, 255, 255, 0.8);
    margin-top: 30px;
}

I know this question is a million times out there, however I can't find a solution to my case. I've got a div, which should be fixed on the screen, even if the page is scrolled it should always stay CENTERED in the middle of the screen!

The div should have 500px width, should be 30px away from the top (margin-top), should be horizontally centered in the middle of the page for all browser sizes and should not move when scrolling the rest of the page.

Is that possible?

Answer

Maciej Krawczyk picture Maciej Krawczyk · Sep 21, 2015

The answers here are outdated. Now you can easily use a CSS3 transform without hardcoding a margin. This works on all elements, including elements with no width or dynamic width.

Horizontal center:

left: 50%;
transform: translateX(-50%);

Vertical center:

top: 50%;
transform: translateY(-50%);

Both horizontal and vertical:

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

Compatibility is not an issue: http://caniuse.com/#feat=transforms2d