Ten Simple CSS Tips

After deleting the 1,400 some odd unread emails I had waiting for me from the css-discuss mailing list I am again able to read the list without feeling overwhelmed. At least until the mails pile up again after a few weeks.

But why would you care about that? Well, shortly after I did that I noticed an interesting request from Scott Wilcox for people’s top CSS tips. So I figured I’d take a shot at seeing if I could come up with 10 hints that would be useful to people at all levels of CSS knowledge. Here’s what I ended up with, is there anything I missed?

  1. Evaluate and clean up your markup before attempting to style anything.
  2. Start all your [base] style sheets with * {margin:0; padding:0; } and only add back what you need where you need it. This cuts down tremendously on the need to fight differences between default browser style sheets and your own layouts.
  3. Use plenty of test styles like extra borders or background colors when building your documents or debugging layout issues. div { border:1px red dashed; } works like a charm. There are also bookmarklets that apply borders and do other things for you.
  4. Learn how to use Firefox’s DOM Inspector or similar tools for other browsers to inspect both the document tree (DOM) and the style rules that are applied to each element.
  5. Move ids and class naming as far up the document tree as you can and leverage contextual selectors as much as possible. Don’t be afraid to be verbose in your selectors. Longer selectors can make css documents easier to read while also cutting down the chances of developing class- or divitis.
  6. Create a page of sample content that contains all of the HTML tags you can think of in different situations (nested lists, block quotes, pre formatted text, definition lists) and use that to check your style sheets for completeness
  7. Never add graphics via <img> that you can style with background-image instead but don’t forget that <img> are in some cases legitimate content.
  8. Learn what a containing block is and how position:relative can manufacture an origin for you.
  9. Don’t get caught up in a desire to “hack” using browser targeted syntax filters or use “tricks” like image replacement techniques
  10. Play. Play with background images. Play with floats. Play with positive and negative margins. Play with inheritance and cascading rules. Play.

[For a much older piece on a similar topic see A Quick Guide To Making Style Sheets Work.]

UPDATE: Translator to the stars (and the WaSP), Kazuhito Kidachi, has translated this post to Japanese.

Comments Temporarily(?) Removed