I have had to work on a project that was written by someone else, and the way they wrote the site everything is positioned using margins, both positive and negative margins.
I only ever really use margins for textual elements like <p> or <h1> tags.
Using padding to space the contents within my div building blocks.
I have come across a lot of issues when margin has been used on divs to try and control the spacing of them.
So my question is:
Is it best practice to only use margins on textual elements, and use padding on the main building blocks unless it makes more sense to use margins on that particular case?
I am interested on other peoples opinions of the margin attribute and it’s uses.
Has it caused anyone else issues?
The CSS
marginattribute should be used to set gaps between boxes, not to position the text (content) inside a certain box and not to alter the positioning of a box. For each of these two activities there are specific properties:paddingandposition(withleft,right,top,bottom).Deciding which of the properties you need is fairly simple. Lets take some cases:
A. I have 3 columns inside a parent and I want them to have some space between them.
This will require using
marginbecause you clearly need space between the elements, not inside them.B. Each of the columns has a border and text content, but the text content starts right from the border. What do I do?
You apply some
padding. Even if you don’t have borders and want to position the text content, you still apply padding, and not margin!C. I want to make some cool futuristic layout, with boxes that aren’t aligned next to each other. Some of them should even overlap!
In this situation it’s clearly not a problem of spacing, but one of positioning, so you should use the, you’ve guessed,
positionproperty. Don’t apply margin to space elements one from another, but rather position them relative to a parent (or to their default position if usingposition: relative).Tip: To make it easier to decide if you need margin or padding always think about what would you do if your you had borders on all elements.
Mandatory reading: http://www.w3.org/TR/CSS2/box.html