5

I have a single div in a page. Now, when I specify its position as absolute and give its margin-left == 20px:

I understand that. The div element should shift right by 20 px so that thee exists a margin 0f 20px between the div and the body.

Now when I provide margin of 20px from right side, shouldn't the whole div move towards right side with a gap of 20px from the body.

http://jsfiddle.net/2Jfpj/

.container{
position: absolute;
background-color:gray;
margin-right: 50px; 
height: 200px;
}

I know I can position the div giving values of left and right. But the real question is margin left works but margin-right doesnt! WHy is it so? Help appreciated!

Navneet Saini
  • 934
  • 4
  • 16
  • 33
  • 1
    why not just use `left` and `right` instead of margin? – Pete May 09 '13 at 13:58
  • @Pete But why doesnt margin-right work here when margin-left is working? – Navneet Saini May 09 '13 at 14:03
  • 1
    have a look at the accepted answer: http://stackoverflow.com/questions/9998260/css-absolute-position-wont-work-with-margin-leftauto-margin-right-auto – Pete May 09 '13 at 14:07
  • I think that the space you think is `margin-left` on your element is actually on the `body` element. Does [this fiddle](http://jsfiddle.net/2Jfpj/3/) remove it for you? – Blazemonger May 09 '13 at 14:28

2 Answers2

9

Its not margin-right you are looking for it is just right

Please see from my fiddle update: JSFIDDLE right

And if you want it to sit at the bottom of the screen add bottom

Try this updated fiddle: JSFIDDLE bottom

Margin-right does not work because it add margin to the div area itself, while right is a position value.

If you look at the box model it shows you where the margin is added to. So Margin is really used to give the box space from other objects around itself.

Andrew
  • 1,850
  • 14
  • 18
  • @NavneetSaini margin-right moves the elements that are to it's right 20pxs away from it, margins simply push the element away, if you want it to be on the right side while being absolute you have to use right, otherwise float:right; – Patsy Issa May 09 '13 at 14:04
0

margin-left works because by default the box is aligned with the left:; property. Set the right:; property than u can set a right margin. But so far i can only set left or right margin on absolutely positioned elements. And therefore you can just use left or right, there is no need for margins. If you figure out how to set left and right margins at the same time, please post how!!!

user1641252
  • 671
  • 5
  • 2