June 20, 2009 2

Refactoring your CSS styles to comply with the DRY principle

By admin in css

When the DRY principle is applied successfully, a modification of any single element of a system does not change other logically-unrelated elements

Every half-decent PHP, Ruby, Python or Java programmer knows and hopefully uses software design principles to design software, Software design principles and design patterns. While design patterns apply mostly to OOP languages and provide programmers with a general reusable solution to common mostly architectural problems software principles like the aforementioned DRY principle can and should be used on a broader scope.

CSS, in contrary to those mentioned languages is mostly used by designers instead of programmers, hence the lack of formal principles.

I think that being a css developer, you can benefit a lot from knowing certain software principles and incorporating them into your daily workflow and enrich your knowledge and abilities beyond random “best practices” lists.

What is DRY about?

The DRY code philosophy is stated as:

Every piece of knowledge must have a single, unambiguous, authoritative representation within a system.

Why should you care?

CSS is per definition and design a complete violation of the DRY principle: Don’t Repeat Yourself, in CSS repetition and redundancy are volitionally built in and encouraged from the start. When writing code of any kind one of the most important and fundamental principles of software design is trying to avoid repetition and redundancy. When the same piece of information appears in more than one place it is bound to get out of sync sometime. Changing or fixing something requires you to fix it in ALL instances which, if you have ever coded anything, a major source for future bugs and malfunction.

If you find yourself doing a copy/paste while you’re coding, you’re likely doing something wrong

Imagine a website with 100.000 visitors/month, assuming you can save only 5kb by DRYing up your css this will result in 5.8Gb less traffic a year.

Programming languages like PHP, Ruby, Python or Java provide a wide array of mechanisms to avoid code repetitions – variables, constants, classes, methods, functions, control structures – good luck emulating those in CSS.

How do I keep my stylesheets DRY?

These are a few random guidelines I use to keep my CSS DRY

  • Rely on inheritance, don’t redeclare inherited values, don’t overspecify, let it flow down the document tree – try setting important XHTML selectors like font and a for your entire site ONCE at the very top of your style sheet and letting them flow through the whole siteW3C Reference on Inheritance
  • Don’t declare default (called “initial” in the specification) values.
  • Group selectors with the same declarations and declarations with the same selectors.
  • Browser hacks always bring redundancy, try to avoid as much as possible.
  • Define everything as globally (as high up the document tree) as possible, assign your classes and IDs at the highest level possible
  • You can assign multiple class names to a given element
  • Reduce redundancy by using shorthand declarations – Sitepoint CSS Reference
  • Use descendant selectors to get specific without class or id selectors. Learn about all the CSS3 selectors, it’s almost like XPath :-)Selectors Level 3
  • If you don’t/can’t use php for variables you can maintain a color scheme reference, change colors with “search & replace”
  • Learn to exploit the cascading nature of CSS – W3C Reference on Cascading
  • Learn about CSS Specificity and how you can calculate the weight of your selectors, this is usually the reason why your CSS-rules don’t apply to some elements, although you think they should have. Generally try to avoid inline styles.
  • You can change capitalisation using CSS
  • Emulate css variables with php – Generating Dynamic CSS with PHP by Douglas Clifton
  • Use a css preprocessor to nest css rules within each other
  • Favor built-in HTML elements before using divs and spans – HTML5 elements
  • Nest css blocks – for details see this article by Matthias Miller

While there is a recommendation for css variables by Daniel Glazman and David Hyatt of Apple, Inc. until this will be available to use in the real world years will pass by. Fortunately there is a way to use all that cool stuff right here right now – with the help of php, ruby and/or css preprocessors

CSS preprocessors – PHP/Ruby

There are a lot of very good css preprocessors out there which can assist you in DRYing up your css workflow.

  • Allain Lallonde’s excellent php snippet which besides allowing you to nest CSS rules within each other gives you the ability to use // for comments.
  • CSS Cacheer a CSS server-side pre-processsor written in PHP by Shaun Inman.
  • css_dryer, a Ruby script by Andrew Stuart, which not only allows you to use nested declarations and css variables but also implements caching.
  • Also for Ruby is SASS (Syntactically Awesome StyleSheets), a meta-language on top of CSS that’s used to describe the style of a document cleanly and structurally, with more power than flat CSS allows. Sass both provides a simpler, more elegant syntax for CSS and implements various features that are useful for creating manageable stylesheets.

Beware of DRYitis

Aside from the fact that DRYitis is not a real word and I totally made that up after a little while you feel inclined to DRY up everything.

Besides all the benefits of a DRY approach one word of caution should be mentioned nevertheless. Adhering to DRY, the potential for taking it too far and sacrificing maintainability is not far away. Sometimes it just makes sense to keep seemingly identical things separated for the sake of maintainability. It might not be a bad idea to put a comment in the code to let future maintainers know that there’s similar code elsewhere that they should fix.

Tags:

2 Responses to “Refactoring your CSS styles to comply with the DRY principle”

  1. [...] Don’t repeat yourself, try to keep your CSS styles DRY. [...]

  2. keyur patel says:

    DRY for CSS, awesome concept, thanks

Leave a Reply

Comment Spam Protection by WP-SpamFree