So you have to write some CSS

I get it. You’re a python/ruby/java engineer, and you’re building your awesome webapp. The problem is, a webapp needs CSS. And you know… just enough to realize how little you know.

CSS is complicated. It’s not a programming language strictly speaking, but you would probably rather it was; you have learned new languages in the past. But CSS is off in its own little world, a wildly complicated set of rules. Sure, you can usually make a page do what you want. Other times leave you completely baffled and out of your element. You wish you had time to read up on how to do it well, but you have code that needs writing.

So here you go. Here are a handful of nice and easy rules for you. Follow these, and your CSS should be… more presentable than if you didn’t. It will be more maintainable into the future, and that front end engineer your startup will hire as soon as it can afford to will thank you. (Because that engineer may be me!)

  • Make your selectors as generic as possible — Use the shortest selector you can, and apply rules as universally as is reasonable. Say you’re adding a dialog box on your billing page. Don’t specify #billing .dialog if you’ll likely want the same CSS for dialog boxes later on; just use .dialog. (This isn’t completely absolute: if you know you’re dealing with an exception to the rule, keep it specific.)
  • Don’t use !important — Like tribbles, these things are born pregnant, and will multiply faster than you can imagine. Instead, take five minutes to learn how selector specificity works and use the browser dev tools to see which rule is overriding the one you want.
  • Minimize duplication — You organize your code into reusable functions; do the same with your CSS. This is kind of a corollary to the two points above.

    Say you have generic dialog box .dialog { color: blue; }, which is overridden on your billing page with a special rule #billing .dialog { color: red; }. If you later find yourself adding another rule like #account .dialog { color: red; }, STOP!

    Instead, make something reusable: .dialog-important { color: red; }. Then you don’t need to touch your CSS yet again when you encounter a third page that needs the same thing!

  • CSS must be refactored — Just like your code, CSS rots. Don’t be afraid to tear down and restructure as things evolve.

Comments

Leave a Reply

Explore