user1452062
user1452062

Reputation: 805

Negative margin affects the absolute positioned div on same level

I have a #left, absolute positioned div and 2 other divs on the right side. When I add margin to the #top div on the right side it affects the #left div too. I know there's a margin collapse stuff but is it affects the position:absolute too?

The code is really simple, nothing special, but I can't find the solution.

* {
    padding:0;
    margin:0;
}

#wrapper {
    width:400px;
    height:400px;
    background:gray;
    position:relative;
    margin-left:100px;
}

#left {
    background:pink;
    width:100px;
    height:100%;
    left:-100px;
    top:0;
    position:absolute;
}

#right {
    background:red;
}

#top {
    background:green;
    height:26px;
}

<div id="wrapper">
    <div id="left">Left</div>
    <div id="top">top</div>
    <div id="right">Right</div>
</div>

Jsfiddle: http://jsfiddle.net/9thvLfe0/2/

Upvotes: 0

Views: 719

Answers (3)

EdenSource
EdenSource

Reputation: 3387

Just add this to #top :

float:right;
width:100%;

JSFiddle

Upvotes: 1

Bladepianist
Bladepianist

Reputation: 490

Well, the problem is that your #wrapper is relative and the #left is absolute. By inheritance, #top and #right are also relative. So, adding a negative margin to top in these conditions, it's adding it to #wrapper.

You could change #wrapper to position "fixed" but you would have to manually set the margin/padding to #hide-top because as it is, he will be hidden under #wrapper. Unless you set it like that :

#hide-top {
    position: relative;
    top: 400px;
}

Yet, my solution wasn't to change your CSS but your JQuery. You could just hide #top with the hide() function. See my JSFiddle for example ;).

Upvotes: 0

Yash Thakur
Yash Thakur

Reputation: 1201

Just give the margin to top and give negative margin same to left.

Upvotes: 0

Related Questions