tags:

views:

58

answers:

3

The following example is identical in almost all browsers including IE6:

http://jsbin.com/adica3

#one  {border : 1px solid red;padding:20px}
#two  {border : 1px solid yellow}
p     {border: 1px solid blue;}
.marg {margin: 0;padding: 0}
.padd {margin:  20px}
</style>
</head>
<body>

<div id="one">
  <p class="marg">Padding to div</p>

</div>

<div id="two">
  <p class="padd">margin tp P</p>

</div>

But when I give width to div then second div becomes shorter then first div.

How we should decide which is appropriate?

What browser compatibility issues should I know about?

A: 

I'd make the decision based on what's going to be inside your tags.

For example, is the <p> the only thing that's going to appear inside your div? If so, then it probably doesn't matter.

If there are other elements that will be inside the div, do you want padding around them or not?

As for the modified width, that will probably be due to the different boxing models between browsers.

Damovisa
+3  A: 

Margins are on the exterior, paddings on the interior relative to the border. So obviously if you have something like a background image and text, and you want the text to have space between the edge of the bg image you'd use padding. Same thing with borders.

If you wanted space on the outside in addition to space between the border/bg images then you'd use margins.

If you're not doing anything remotely design-complex then it shouldn't really matter, but one thing you should look out for is margin collapsing, if you have elements coming before/after with vertical margins and you specify margins the values will collapse, sometimes you'd use padding to navigate around that.

If you give #one and #two a width of 200px, #one will take up 240 pixels without counting the horizontal borders, since it has 20px of padding horizontally.

IE5's rendering engine and quirks mode IE6/IE7 incorrectly draw the correct amount of space if you specify horizontal padding and a width, width:100px; padding:20px; would force the box to actually take up 100 pixels of width, instead of actually being 140 pixels as it should correctly be.

Another bug to note is the double margin bug; if you have a floated element and a margin that's in the same exact direction as the float, eg float:left;margin-left:100px; it accidentally doubles up. This is fixed by adding display:inline; which forces it to just have 100px instead of 200px to the left.

I notice that you ask a lot of questions which would be answered by simply reading a decent front end book - have you considered reading:

Those would probably answer a lot of your questions...

meder
A: 

i think the easy way is thinking the border of the element.

margin spaces outside border, while padding inside.

Of course, there are some browser related issue made them difference in some way, but i suggest stay with my suggestion and find work around on those special browsers.

joetsuihk