On refactoring 8 lines of CSS.
Yesterday, I spent a few hours refactoring CSS. Specifically, I replaced 8 full rules along with parts of a number of other rules with 7 new rules. The CSS rules impact every single form field over 5 sites. I didn’t alter any HTML and visually the best part is that every form looks identical to it’s original, with the exception of fixing a bug in Firefox, another in Internet Explorer and improving visual consistency across browsers and elements, while eliminating some browser specific hacks and !important declarations.
It doesn’t sound like an enormous refactoring success. After all, why spend hours refactoring CSS to merely replace 8 old lines of CSS with 7 new lines?
The secret lies in selector specificity. The original CSS selectors targeted inputs nested within divs to which a certain class name is applied. The new rules target inputs based on their specific class and type, defining in the process 3 core base styles of input elements.
We have an assortment of forms and input fields spanning 5 sites, each with a variety of types of styling applied. Every form has been manually fine-tuned to ensure visual consistency with the original design. The problem is, it’s impossible to create an input element, add a specific class and know precisely what the result will be. It’s also relatively impossible to make a change in the CSS that impacts all form elements of a specific type and class without conducting a thorough search through each form visually inspecting it to ensure that the alterations haven’t been overridden by styles applied to an individual form.
In reality this was only a beginning step in refactoring all form elements and forms over the hundreds of thousands of pages of our sites. The 7 new CSS rules will allow us to eliminate an exponentially larger number of rules because they are the foundation for building a highly flexible modular system for our HTML forms that will enable our UX designers to quickly and efficiently code and prototype new forms without starting from scratch each time.
- Shoot to kill; CSS selector intent, by Harry Roberts
- The media object saves hundreds of lines of code, by Nicole Sullivan
- Refactoring for designers, 37Signals
The following books are more theoretical in nature with concepts applying indirectly to CSS refactoring.
- Refactoring: Improving the Design of Existing Code, by Martin Fowler.
- The Pragmatic Programmer: From Journeyman to Master, by Andrew Hunt