Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Negative margins vs relative positioning

I've come across many layout techniques involving negative margins, such as this classic for sidebar positioning. It seems like these techniques could just as easily be applied with relative positioning.

So instead of this:

.sidebar {     margin-left:-600px; } 

One would do this:

.sidebar {     position:relative;     left:-600px; } 

It seems like relative positioning might even be cleaner in the vertical direction, as top-margin manipulation may be affected by collapsing margin issues, etc.

Is there any advantage to one over the other, or are they practically equivalent?

Thanks-

like image 618
Yarin Avatar asked Mar 10 '11 06:03

Yarin


People also ask

What are negative margins?

The margin is described as negative or clean when the pathologist finds no cancer cells at the edge of the tissue, suggesting that all of the cancer has been removed.

What is relative positioning?

Relative Position: Setting the top, right, bottom, and left properties of an element with position: relative; property will cause it to adjust from its normal position. The other objects or elements will not fill the gap.

Should I use relative or absolute positioning?

As a special, use “relative” positioning with no displacement (just setting position: relative ) to make an element a frame of reference, so that you can use “absolute” positioning for elements that are inside it (in markup).

What is the difference between relative positioning and absolute positioning?

Relative - the element is positioned relative to its normal position. Absolute - the element is positioned absolutely to its first positioned parent. Fixed - the element is positioned related to the browser window. Sticky - the element is positioned based on the user's scroll position.


2 Answers

I guess relative positioning will shift the content to left but the original space will be occupied by it unless you make the next element relative too. However with negative margin the content and its original space both are shifted.

like image 134
Anupam Avatar answered Oct 14 '22 10:10

Anupam


Put (more) simply, relative positioning will visually shift the contents of the relative element, without affecting its place in the page flow. Margins, on the other hand, push or pull elements relative to their natural position, and so affect layout.

like image 24
Yarin Avatar answered Oct 14 '22 11:10

Yarin