Patrick Reck
Patrick Reck

Reputation: 11374

position:absolute follows other elements margin

I have a #background and a #content box. The #background is supposed to be at top, and #content box have a margin-top of X pixels.

Now, the problem is that even though #background have the position: absolute; property, it follows the #contents margin.

Why is the #background affected?

HTML

<div id="background"></div>

<div id="content">Content</div>

CSS

#content {
    width: 200px;
    margin: auto;
    margin-top: 150px;
    background-color: Coral;
}

#background {
    width: 100%;
    height: 500px;

    position: absolute;

    background-color: AntiqueWhite;

    z-index: -1;
}

Reproduced problem http://jsfiddle.net/GeU35/

Upvotes: 0

Views: 41

Answers (3)

Ruddy
Ruddy

Reputation: 9923

So you just needed to set its position via top: 0;. Remember you can add left: 0; to make it sit to the left as well. Also anyway you want. bottom: 0; and right: 0;.

CSS:

#background {
    width: 100%;
    height: 500px;
    position: absolute;
    top: 0;
    left: 0;
    background-color: AntiqueWhite;
    z-index: -1;
}

DEMO HERE

Upvotes: 1

Steve N.
Steve N.

Reputation: 21

It's an interesting effect, but ultimately you have specified an absolute position, then not given any position information. I believe that's why it misbehaved. As mentioned in other answers simply setting something like top:0px solves it readily.

Upvotes: 0

jonsuh
jonsuh

Reputation: 2875

Not quite sure if I understand, but will doing this fix your issue? Ultimately setting top: 0 and left: 0 to #background

#background {
    width: 100%;
    height: 500px;

    position: absolute;
    top: 0;
    left: 0;

    background-color: AntiqueWhite;

    z-index: -1;
}

Upvotes: 1

Related Questions