Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

  • the creation of additional nonsemantic markup
  • applying the same top: -50px rule to all subsequent elements on the page
  • using any kind of magic number on my CSS.

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.

like image 916
Fabio Bracht Avatar asked Oct 19 '22 02:10

Fabio Bracht


2 Answers

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/

like image 143
Nicholas Hazel Avatar answered Oct 21 '22 22:10

Nicholas Hazel


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/

like image 40
pgruber Avatar answered Oct 22 '22 00:10

pgruber