How to compensate for the space left by a relatively positioned element? (No mess)

I have three elements:

enter image description here

Now my layout requires that the .b element (by the way, if it is important, they are all html <section> s) overlap a bit on the .a element. So I decided to apply position: relative to it, then push it using top: -50px .

What's happening:

enter image description here

I successfully overlaid the top two elements, but now I have created an unnecessary 50px space between .b and .c . (They should have been glued.)

My first assumption was to use the equivalent margin-bottom: -50px , but that didn't work, for some reason I don't know either.

In the end, I resolved this by a roundabout path by making .b child of .a . This caused an overflow of .a above .c , but then I applied the magic number margin-bottom to it to push .c back.

Of course, I am not happy with this decision, so I ask here.

What would you say is the best way to solve this problem?

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

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

I just want to learn the best practice when I do this because I assume that this will be a problem that I will face more than once in the future.

+5
source share
2 answers

So, a few ways to do this.

My suggestion would be to use margin-top for the element you want to overflow. Everything else will display correctly, and only one item must be installed correctly.

Visual presentation:

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; } 

An example is given below:

http://jsfiddle.net/dp83o0vt/

+2
source

Instead of installing

 top: -50px; 

just install

 margin-top: -50px; 

This way your .c still adheres to .b and you don't have to get confused.

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

+1
source

All Articles