Search code examples
cssheadercenterfixed

CSS: Any way to horizontally center a header which has "position:fixed"?


I have a header created with two div containers, one #header-container and one #header:

#header_container { 
background:#eeeeee; 
border:0px hidden; 
height:100px; 
position:fixed; 
width:1000px; 
top:0; 
margin: auto; 
display: block;
}
#header { 
line-height:60px; 
margin:0 auto; 
display:block; 
width:940px; 
text-align:center;
}

I am of course unable to have both "fixed" and "center", so how can I center the header while keeping the "fixed" property?

Thanks!


Solution

  • If you add "left: 50%;margin-left: -500px;" to #header-container, it will center. Don't forget to place the margin-left behind the margin: auto;

    So your code will be:

    #header_container{
    background: #eeeeee;
    border: 0px hidden; 
    height: 100px;
    position: fixed;
    width: 1000px;
    top:0;
    left: 50%;
    margin-left: -500px;
    display:block;
    }
    
    #header{
    line-height: 60px;
    margin: 0 auto;
    display: block;
    width: 940px;
    text-align:center;
    }