Forum Moderators: not2easy

Message Too Old, No Replies

position versus margin?

         

welkin

6:25 pm on Aug 3, 2005 (gmt 0)

10+ Year Member



hi all. i'm kind of new to css layout... so say if i have an element on the page that i want to place 50 px from the left edge, should i use "position:relative;left:50px" or "margin-left: 50px"? what's the difference? thanks in advance~

Pixelgamer

7:18 pm on Aug 3, 2005 (gmt 0)

10+ Year Member



Well, if there isn't anything else between the elft edge and your object you wanna position, there is no differneces in these two approaches, either works fine.

The difference is that the position: absolute; left: 50px; doesnt care about other objects on your site, it just places this object 50 pixels from the elft edge, but margin-left: 50px; places your object 50 pixels left, of any other object that happens to left to it. (Hence making a sort of invisible border 50 pixels wide on the left side.)

welkin

7:56 pm on Aug 3, 2005 (gmt 0)

10+ Year Member



thx. but what about position:relative?

createErrorMsg

9:04 pm on Aug 3, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



position:relative positions the element at it's normal location in the document flow, and then subsequently moves it to the offset position. The space it originally occupies is reserved in the layout (left empty), whereas with position:absolute, the element is removed entirely from the flow and no space is reserved (so other elements will fill it in as if it weren't there).

Margins, on the other hand, are not positioning properties, but part of the box model used to create block boxes on the page. The margin is the space that exists between the border edge of an element, and the border edge of the next adjacent element.

For me, the decision would come down to how I would word a description of what i'm trying to do. If I would describe the effect I'm after as "position the element 50px to the right," I would use position:relative;left:50px;. If, on the other hand, I would more accurately say, "place 50px of space between this element and the one on it's left," I would use margin-left:50px;.

This may seem pedantic, but really it's about putting tools to their best use. The description you use in your own head will reflect what you are thinking about the layout, and what you are thinking about the layout will, in all likelihood, reflect the property you need.

One thing to bear in mind regarding margins, however. When two margins meet with no border between them, they combine together to form one margin equal to the largest of the two. This is refered to as collapsing margins [w3.org]. If the container holding the element to which you apply a 50px margin also has a left margin, the two could postentially collapse, ruining the effect you're after.

Try whichever option feels most right to you, then test it on several browsers and see how it works.

cEM