I wanted to share the CSS tips and bugaboos I've articulated for myself (and my team) over the past few weeks:
- Use a dynamic stylesheet language. I don't care which one - sass, less or something else - but use a stylesheet language. CSS is much easier when you can use variables, mixins, and other things we programmers take for granted elsewhere. Plus, who really likes doing search and replace on hex codes?
- No bare text. Don't use text that's not in a container of some sort. It will be affected by any styling changes that affect the body text, which tends to lead to unintended consequences. In addition, bare text is a lot harder to place appropriately on the page. Put it in a span or a div or a p or something - anything!
- No br tags. I'm not a fan of
tags. That's mixing layout and content, which I think is a bad idea, even on a static page. If you really want a line break, it's almost certainly because you're changing to a separate type of content - another paragraph, or another item in a list. That means you should make it a paragraph or a list. Oh, and if you really must use the br tag, at least close it!
- html_safe is a minor code smell. The project is a Rails project, but other languages have equivalents. Using "FooBar".html_safe is an indication that you're doing something odd. This can open up a security hole if any of the contents are user input. And if you're not using user contents, then you're probably putting html tags inside a single element - again mixing content and layout, which is not a good idea.
- Lists are your friend. Not all lists have bullets or numbers. They're really useful for any layout that is sequential, horizontally or vertically. That means navigation menus, sequential results, etc.
- Deep is bad. Particularly when you're using a CSS layout (e.g., Bootstrap) and/or a lot of different backgrounds, it gets really easy to nest a lot of divs to achieve a layout. As the application grows it will start to show in the render time of the page. Use as few divs as possible for simple positioning, and see if there's a way to make them shallower where possible.
A lot of these thoughts tie back to a separation of concerns. Content, layout/markup and styles are three different things and should be handled in three different places. You create a layout in your views, inject content from the controller (using an MVC framework or similar), and style it with your stylesheet language (ultimately CSS). Don't mix them.
What are your CSS-related bugaboos?