I have these three elements:
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:
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:
top: -50px
rule to all subsequent elements on the pageI 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.
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:
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/
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With