Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where do you put your CSS Margins? [closed]

Tags:

css

margin

When you want to add whitespace between HTML elements (using CSS), to which element do you attach it?

I'm regularly in situations along these lines:

<body>
  <h1>This is the heading</h1>
  <p>This is a paragraph</p>
  <h1>Here's another heading</h1>
  <div>This is a footer</div>
</body>

Now, say I wanted 1em of space between each of these elements, but none above the first h1 or below the last div. To which elements would I attach it?

Obviously, there's no real technical difference between this:

h1, p { margin-bottom: 1em; }

...and this...

div { margin-top: 1em; }
p { margin-top: 1em; margin-bottom: 1em }

What I'm interested is secondary factors:

  1. Consistency
  2. Applicability to all situations
  3. Ease / Simplicity
  4. Ease of making changes

For example: in this particular scenario, I'd say that the first solution is better than the second, as it's simpler; you're only attaching a margin-bottom to two elements in a single property definition. However, I'm looking for a more general-purpose solution. Every time I do CSS work, I get the feeling that there's a good rule of thumb to apply... but I'm not sure what it is. Does anyone have a good argument?

like image 856
Craig Walker Avatar asked Sep 19 '08 22:09

Craig Walker


2 Answers

I tend to use a bottom margin on elements when I want them to have space before the next element, and then to use a ".last" class in the css to remove the margin from the last element.

<body>
  <h1>This is the heading</h1>
  <p>This is a paragraph</p>
  <h1>Here's another heading</h1>
  <div class="last">This is a footer</div>
</body>
div { margin-bottom: 1em; }
p { margin-bottom: 1em; }
h1 { margin-bottom: 1em; }
.last {margin-bottom: 0; }

In your example though, this probably isn't that applicable, as a footer div would most likely have it's own class and specific styling. Still the ".last" approach I used works for me when I have several identical elements one after the other (paragraphs and what-not). Of course, I cherry-picked the technique from the "Elements" CSS framework.

like image 118
Pavling Avatar answered Oct 15 '22 19:10

Pavling


Using advanced CSS 2 selectors, another solution would be possible that does not rely on a class last to introduce layout info into the HTML.

The solution uses the adjacent selectors. Unfortunately, MSIE 6 doesn't support it yet so reluctance to use it is understandable.

h1 {
    margin: 0 0 1em;
}

div, p, p + h1, div + h1 {
    margin: 1em 0 0;
}

This way, the first h1 won't have a top margin while any h1 that immediately follows a paragraph or a box has a top margin.

like image 31
Konrad Rudolph Avatar answered Oct 15 '22 18:10

Konrad Rudolph