Hacker News new | ask | show | jobs
by Facens 5550 days ago
My main rule is: Never write a class that you can't use again. I've other rules too, such as "padding is top, margin is bottom". CSS must be modular, not exception-based.
3 comments

That's interesting. I've always wondered if some people had conventions on when to use padding and when to use margin, since you can almost always accomplish the desired effect either way.
Except that adjacent vertical margins collapse on each other, so the space is the larger of the 2 margin values not the sum.

more info: http://reference.sitepoint.com/css/collapsingmargins

This is not true of padding (unless you count a bug in IE8 where percentage-based padding-bottom collapses on the margin-bottom)

If you want to be modular, you must have conventions. This is to prevent double spacing when you put two elements one next to another without additional styling. I also use to have ELEMENT > *:first-child {padding-top: 0} on containers, so that I can control the padding of the container and without having to consider what element I place into it. There's a lot of best practices I made part of my workflow, perhaps I should write a blog post about it.
You can't really. CSS backgrounds are the main reason you need to use padding (instead of margin): margins exist outside an element, while padding expands within the box itself (beyond the content, but permitting the background to remain visible).

To visualize it, http://hicksdesign.co.uk/boxmodel/ is probably the most oft-cited example - certainly the one I find most helpful.

Ok, I was talking about transparent elements, where in fact you have complete choice (at least if you have no borders too).
In my experience, that is almost never the case, except when you're faking margin by using padding.

In that case, use margin.

Another best practice I have is to place a comment on each closing element, referring to the opening one. So,I have: <div class="CLASS"> CONTENTCONTENTCONTENT </div> <!-- .CLASS -->

When you have complex pages, with several nesting levels, this can save much, much time.

Isnt there a danger that someone else working on your code might not respect that rule (or dare I say it, but maybe you're in a rush one day) and you don't update the comment when you update the class.

Now you've got comments saying in correct things, and you risk all sorts of confusion.

The same rule applies to commenting methods in code really, you don't comment what the code does exactly - just what the intention of the code is.

The time spent on keeping the code readable is never wasted :) Obviously, every developer must adopt this habit.
Top and bottom of the box, or top and bottom in the source? Margin and padding are both useful on all sides of the box.