Forum Moderators: not2easy

Message Too Old, No Replies

Best way to move a div 20px right

Is it better to use "margin-left:20px" or "position:relative;left:20px;"?

         

orfest

5:36 am on Jul 11, 2007 (gmt 0)

10+ Year Member



What is the very best way to say "This div should be moved to the right on 20px"?
Should I use "margin-left:20px;", "padding-left:20px;" or "position:relative;left:20px;"?

DrDoc

5:46 am on Jul 11, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Well, it entirely depends on how you want the div to move.

margin-left
This tells the div to simply leave some more space on the left side. "Move over a tad, will ya?" Margin is what you want to use whenever you want to change the spacing around (or on at least one of the sides of) an element. Want some space between an image and surrounding text? Margin. Want to increase whitespace between blocks of text? Margin.

padding-left
In a borderless environment, padding will appear to do the same as margin ... but it only appears that way. Just like margin increases spacing, so does padding. But whereas the margin increases the spacing on the outside of the element, padding increases spacing on the inside. Does that submit button need some spacing between the button text and the button edge? Padding. Does that nicely bordered element need some extra air? Padding.

Important: Padding is part of an element, whereas margin is the repellant space around the element ... room to play, so to speak. Margins collapse, padding doesn't. (Collapsing means that if two elements next to each other both have a margin defined, the larger margin of the two will be used.)

position: relative
Relative positioning is a purely visual effect. It does not actually increase/affect any spacing. In fact, a relatively positioned element still resides in its original location, but is rendered elsewhere. To provide a simple example. Imagine two images side by side. The left image has

position: relative
defined, with a
left
value of 20px. Although this will truly shift the left image 20 pixels to the right, it will have no effect whatsoever on the right image. The right image will still think that the left image is in its original location. Hence, the two will overlap by 20 pixels.

[edited by: DrDoc at 5:47 am (utc) on July 11, 2007]

orfest

6:00 am on Jul 11, 2007 (gmt 0)

10+ Year Member



Thanks!

I see, that now I need not only "optimize CSS", but also to correct some dirty things.

DrDoc

6:09 am on Jul 11, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



... and kudos to you for doing so!

The faster you start "doing things right", the faster things will begin to make sense. And, eventually you will know when to do what, and how to do it, like the back of your hand. :)