ivvi
ivvi

Reputation: 5310

margin affects other fixed elements position

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>

Upvotes: 14

Views: 13868

Answers (4)

user1413795
user1413795

Reputation: 1

Or set the top padding (instead of top margin) for #content to be the height of #header.

We have figured the ways to correctly position the header, but I'm still very curious why the offset happened at the first place.

Upvotes: 0

Zensar
Zensar

Reputation: 817

I believe you are feeling the affects of "margin collapse", which is causing your "margin-top" entry in "content" to collapse into the body element of the page. An easy fix is to just create a containing div around "content" and "header" and set the CSS to "overflow:hidden". Then, be sure to set the margins and padding of the "body" element to 0.

Upvotes: -1

Jeff
Jeff

Reputation: 14279

#content is fixed position, but the coordinates that you set for top, right, bottom and left are relative to its parent container: #header. In other words, #content is always going to be fixed to the top of #header. Since you are bumping #header down with margin, the #content will follow.

You either need to offset the margin

#content { position: fixed; top:-25px; }

That said, I assume you want to fix something to the top of the screen and I don't think this is going to get you what you want. You'll need to break #content out of #header or else make #header statically positioned: position:static so that the content is fixed to the top of the window, not the header.

Upvotes: 0

Seabass
Seabass

Reputation: 1973

#header {
    top: 0px !important;
}

Upvotes: 12

Related Questions