Fabio Bracht
Fabio Bracht

Reputation: 423

How to compensate for space left by a relatively positioned element? (Without making a mess)

I have these three elements:

enter image description here

Now, my layout mandates that element .b (by the way, if it's important, they're all html <section>s) is somewhat superimposed on element .a. So I decide to apply position: relative to it, then nudge it up using top: -50px.

What happens is this:

enter image description here

I successfully superimposed the two top elements, but now I created an unnecessary 50px space between .b and .c. (They were supposed to be glued together.)

My first guess was to apply an equivalent margin-bottom: -50px, but this didn't work, for some reason I'm also not aware.

Eventually I resolved it in a roundabout way by making .b a child of .a. This caused .a to overflow above .c, but then I applied a magic number amount of margin-bottom to it in order to push .c back down.

Of course, I'm not happy with this solution, so I'm asking here.

What would say is the best way to resolve this?

By best way I mean I want to avoid, if possible:

I just want to learn the best practice when dealing with this, because I assume it's going be a problem I will be encountering more times in the future.

Upvotes: 5

Views: 284

Answers (2)

Platte Gruber
Platte Gruber

Reputation: 3193

Instead of setting

top: -50px;

simply set

margin-top: -50px;

This way your .c still sticks to .b, and you don't have to mess with anything else.

jsfiddle here: http://jsfiddle.net/gyrgfqdx/

Upvotes: 1

Nicholas Hazel
Nicholas Hazel

Reputation: 3750

So, several ways to accomplish this.

My suggestion would be to utilize margin-top on the element you want to overflow. Everything else will render properly and only one item needs to be positioned properly.

Visual Representation:

enter image description here

HTML

<div id="one">Item 1</div>
<div id="two">Item 2</div>
<div id="three">Item 3</div>

CSS

#one, #two, #three {
    position: relative;
    margin: 0 auto;
}
#one {
    width: 400px;
    height: 200px;
    background: #ABC;
}
#two {
    width: 200px;
    height: 100px;
    background: #CBA;
    margin-top: -50px;
}
#three {
    width: 400px;
    height: 300px;
    background: #BBB;
}

Example provided here:

http://jsfiddle.net/dp83o0vt/

Upvotes: 2

Related Questions