Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS, nested divs & margins vs. padding

i totally understand the box model. this question is more about trying to pin down a semantic methodology regarding when to use margins and when to use padding.

here is a typical example,

first, in plain English:

  • situation: we have a container div, inside of which there is a paragraph element.
  • goal: to have a 12px space between the inside of the div and the outside of the paragraph.

  • option a) apply 12px of padding to the container div

  • option b) apply 12px margins to the paragraph element

or, if you prefer, HTML:

<div id="container">
    <p>Hello World!</p>
</div>

and, CSS:

option a)

div#container {padding: 12px;}

option b)

p {margin: 12px;}

Cheers!

Jon

like image 950
jon Avatar asked Dec 13 '22 02:12

jon


2 Answers

Paddings and margins gives the same effect, Except in the following cases (I might miss some):

  1. You have some kind of background properties. Margins won't get them.
  2. You have a border
  3. You use TD (no margins)
  4. Two nested items, The margins are collapsed together, where paddings not.
  5. (need to check this one) They probably affect the width and height of the element differently. (If some one knows better, pls edit this).
like image 55
Itay Moav -Malimovka Avatar answered Dec 27 '22 21:12

Itay Moav -Malimovka


Personally, I prefer option A. Why? Say now I have to add other HTML elements into the div and I want the padding to be maintained, I would not have to add other rules to my CSS files to get it working.

like image 31
DLS Avatar answered Dec 27 '22 20:12

DLS