2

When creating HTML5 and CSS3 designs is it better to primarily use margin and padding for your designs over positioning or the other way around?

I've never really thought about it before and use both side by side to get the results where needed but it's possible to design in both ways as shown in the examples below:

HTML

<div> <ul> <li><span>1</span></li> <li><span>2</span></li> </ul> </div>

CSS Example 1 - Using margin, padding

div{
    width:1000px;
    margin:auto;
    }
ul{
    margin-left:10px;
    width:100px;
    }
li{
    height:30px;
    }
span{
    margin-top:10px;
    }

CSS Example 2 - Using just positioning (Apart from the margin:auto ..)

div, ul, span{
    position:absolute;
    }   

div{
    width:1000px;
    margin:auto;
    }
ul{
    left:10px;
    width:100px;
    }
li{
    height:30px;
    }
span{
     top:10px;
    }
Dan
  • 11,914
  • 14
  • 49
  • 112

3 Answers3

2

All of the above. Positioning is good for things that pop out or can be dynamically created. Sometimes the positioning is actually a derived placement. The padding and margins generally are used for how those elements will be placed in relation to other elements. So an item can have padding, margins, and positioning and have all those attributes be relevant to the element.

A common theme is to get the client environment and then design based on relation to their viewable area.

See this link https://stackoverflow.com/a/8857735/1026459 for javascript to get client screen size (cross-browser compliant).

Community
  • 1
  • 1
Travis J
  • 81,153
  • 41
  • 202
  • 273
2

For a typical page layout, Example 1 is much cleaner and you should choose that, given the choice.

Example 2 is bad because as soon as you start setting position: absolute on everything, any flexibility your design may have had goes out the window. You have to set explicit dimensions on everything.

In general (there are exceptions), avoid position: absolute for the main layout unless it's only way to do it.

Here's an example of the kind of problem I was talking about. It would appear that the user ended up using JavaScript to fix his problems. Not good.

Community
  • 1
  • 1
thirtydot
  • 224,678
  • 48
  • 389
  • 349
1

as rule of thumb, position rules are most suitable, as implied by their name.

margins are not very reliable due to their model inconsistency across browsers, thus less adapted for that purpose.

having said that, most layout techniques are a mash-up of both of these, and both are used in conjunction.

Eliran Malka
  • 15,821
  • 6
  • 77
  • 100