How to center a position: fixed header


I am customizing this theme: .

I am trying to make the header (the part with the logo and menu) just 1140px wide instead of 100% and make it centered, but I also want it to remain fixed at the top of the screen. If I remove position: fixed, it will center, but with that applied, it will not.

Is there a workaround for this type of thing?


Try this css code:

#someid {
    position: fixed;
    /* center the element */
    right: 0;
    left: 0;
    margin-right: auto;
    margin-left: auto;
    /* give it dimensions */
    min-height: 10em;
    width: 90%;

That’s a nice solution, @MarPlo. (It also works with the required 1140px width.)

Another option would be this (although I think I prefer MarPlo’s):

.site-header {
    position: fixed;
    left: 50%;
    margin-left: -570px;
    width: 1140px;

The downside of that technique is that as you close the window the left side of the element slides off the left side of the window and is unreachable. Some people used to center whole pages like that and it’s a bit of nightmare on smaller screens.:slight_smile:

I usually use the same technique as MarPlo for both fixed and absolute elements. As long as the element has a width (or a max-width) then left:0 and right 0 will center the element within the containing block (as will top:0 and bottom:0 vertically center the element with a fixed height). It doesn’t work in IE7 though and if IE7 compatibility is needed another option is simply to nest a static element of the desired width inside a 100% wide fixed element and center it in the normal way.

Thanks so much, everyone! That solution works beautifully. :slight_smile: