Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS position fixed AND margin 0 auto

So I have a background image with the following css:

 body{
    background-image:url(cover.jpg);
    background-repeat:no-repeat;
    background-position:center;
    background-attachment:fixed;
}

And the background image is 1280 px in width. So I want my navigation bar fixed and centered with the background. However Im running into issues. Here is my code.

#navigation {
margin: 0 auto;
position:fixed;
top: 0;
width: 1280px;
height: 35px;
padding-top: 10px;
background-color: #000000;
}

But the navigation bar will be fixed but not centered. If I remove the fixed, it will center it but then its not fixed.

Any ways to accomplish this?

like image 269
Jared Avatar asked Feb 27 '14 21:02

Jared


People also ask

Does margin auto work with position fixed?

You can use margin: 0 auto with position: fixed if you set left and right . This also works with position: absolute; and vertically.

What does margin 0 Auto in CSS do?

So in margin: 0 auto, the top/bottom margin is 0, and the left/right margin is auto, Where auto means that the left and right margin are automatically set by the browser based on the container, to make element centered.

How do I set auto margin in CSS?

The auto Value You can set the margin property to auto to horizontally center the element within its container. The element will then take up the specified width, and the remaining space will be split equally between the left and right margins.

What is required for margin 0 Auto to work?

The element must be block-level, e.g. display: block or display: table. The element must not float. The element must not have a fixed or absolute position.


2 Answers

you can make the following

#navigation {
    position:fixed;
    left:0;
    right:0;
    margin-left:auto;
    margin-right:auto;
    width: 1280px;
    height: 35px;
    padding-top: 10px;
    background-color: #000000;
}
like image 117
Moussawi7 Avatar answered Sep 17 '22 00:09

Moussawi7


.fixed-centered {
    position: fixed; 
    left: 50%;
    transform: translate(-50%);
}
like image 31
Catalin Enache Avatar answered Sep 18 '22 00:09

Catalin Enache