Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

margin affects other fixed elements position

Tags:

html

css

I wanted to set a top header in a fixed position and have content scroll underneath it and came across some strangeness. If I set a margin-top to the content div that margin would also affect the header and move it down even though it's set to position:fixed. I found a workaround by setting the content div to position:relative and using top: to offset it the same amount, but I find it strange that a non-nested div can affect a fixed-positioned element and would like to know why it happens.

I get the same thing in Safari, Firefox and Chrome. In Opera the margin pushes down the content and leaves the header in place, which is what I expected it to do, but compared to the other results maybe it's Opera that has it wrong. What I'm talking about can be in seen in this JSFIDDLE (don't use Opera! :) ).

Here's the code:

css:

body {
    background:#FFD;
}

#header {
    position:fixed;
    height:15px;
    width:100%;
    text-align:center;
    border-bottom:1mm dashed #7F7F7F;
    background-color:#EEE;
}

#content {
    width:90%;
    margin-top:25px;
    margin-left:auto;
    margin-right:auto;
    background-color:#E5E5FF;
    border: 1px solid #000;
}

html:

<body>
    <div id="header">
        HEADER
    </div>
    <div id="content">
        <p>Text1</p>
        <p>Text2</p>
        <p>Text3</p>
        <p>Text4</p>
    </div>
</body>
like image 984
ivavid Avatar asked Mar 08 '12 21:03

ivavid


People also ask

Does margin work with position fixed?

Margin does not work because position of the header is fixed.

How do you give a position to margin fixed?

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

Which property is used to change the margin of an element?

The margin-left CSS property sets the margin area on the left side of an element. A positive value places it farther from its neighbors, while a negative value places it closer.


1 Answers

#header {
    top: 0px !important;
}
like image 187
Seabass Avatar answered Oct 16 '22 13:10

Seabass