CSS Architectures: Completing MetaCoax Refactoring

Taming CSS that’s gone wild is no easy task. If you’ve studied any of the top scalable and modular CSS architectures, you may have been simultaneously overjoyed at finding the cause of your team’s CSS woes, yet intimidated by the prospect of how to initiate getting the suggested changes into your documents and workflow.

The MetaCoax CSS refactoring process provides a way to make changes to your CSS over time and in waves as the code gets progressively cleaner and easier to manage. This final article in the CSS Architectures series describes the final two phases of the four-phase process, as well as the success story that came from employing it.

Let’s look at the final steps needed to give your CSS a new lease on a scalable life.

Phase 3: Sleek Selectors, Group and Separate

Phase 3 focuses on making the stylesheet even more lightweight. It continues to eliminate redundancy by fully optimizing selectors and modularizing code, separating the CSS into individual files based on the style category, and creating a style-pattern library and a site style guide. This phase presumes that you’ve implemented phases 1 and 2, as these changes are an additional layer on top of the earlier ones.

Here’s what we’re going to do:

Modularize more

Use state names and JavaScript names for the related classes

Move all styles to the modular level

Sleek selectors

Completely eliminate elements as selectors

Completely eliminate IDs as selectors

Group and separate

DRY (“don’t repeat yourself”) it up

Categorically separate the CSS

Make a plan for @media

Modularize More

The process of identifying and determining modules on your site will probably be ongoing, because patterns will likely become more apparent over time and as you modularize more pieces of the site’s code.

Up to this point, we’ve been doing a great job of cleaning up the old selectors and replacing them with new styles and new selectors that get the job done with fewer lines of code and can be reused across the site. From CSS for Grownups, keeping the styles at the modular level means that they are truly portable and recyclable, relating to the module itself and not tied to a page, page section or container. These few final techniques will ensure that we continue with clean code.

While that work goes on, there are a few more classes you should be sure to institute: states and JavaScript. OOCSS, SMACSS and CSS for Grownups recommend naming classes so that they clearly denote those for states and JavaScript to keep them clear in the stylesheet and easier to find and update.

State Classes

One practice from SMACSS that I like is to use state names when I have state classes for elements. State classes are made to stand alone and are typically a single class selector. For example, a module can be extended by states, such as shown here:

.is-collapsed
.is-active
.is-error
.is-hidden

In SMACSS, the state classes are the only place where !important can (and sometimes should) be used.

If the state rule is made for a specific module, it is recommended to include the name of the module as well in the class name. For example:

.is-navitem-hidden

Personally, I find this syntax awkward. I find that the following syntax is easier to scan and lets me find the ruleset quickly.

Class names like these can reduce the chance that changing the structure or theme of a module or component will inadvertently affect any required JavaScript behavior and complex functionality.

Sleek Selectors

By now, you’ve reshaped the selectors in your stylesheet to get rid of most of their bloat: qualifiers have been dropped, the selectors are no longer based on elements high up in the DOM and the combinators should be three or less. We’re now ready to take it all the way to the final bit of selector cleanup, to make them truly lean and optimized.

Completely Eliminate Tags as Selectors

This recommendation applies to styles that are layout, module, state or theme styles. It does not relate to reset or base styles. You’ve had it beaten into your head by now: element selectors are too closely tied to the HTML structure for it to be at a module or component level, right? So, if there are still selectors floating around your CSS with an element as part of them, figure out how to transform that selector into a straight .class, and make it so.

Completely Eliminate IDs as Selectors

Similarly, if there are any #IDs as selectors in the stylesheet, those styles may be too closely tied to a document itself or a location in the document. More important, it will also mean that the specificity of the selector is too high and will continue to encourage the practice of writing even more specific selectors to override that style—which will start to make the stylesheet long and unwieldy again. Just don’t do it. Get rid of the styles that have #IDs to give them all the same level of specificity once and for all.

Group and Separate

The very last recommendation for revamping your stylesheet is to gain lordly reign over your CSS by putting like with like as you tear the dissimilar asunder.

DRY It Up

The strength of DRY CSS comes from the strength of the idea “don’t repeat yourself.” While I have not found a way to incorporate many of the DRY CSS practices into the MetaCoax process, I do like some of aspects of smart grouping of selectors to get the same style.

For example, if something like font-weight: bold has been repeated numerous times in the stylesheet, I can see a situation where many of the selectors of elements are grouped with {font-weight: bold:} as the main style. However, I would apply this practice as the last in a series of techniques once the selectors for the styles have been fully optimized.

Categorically Separate Your CSS

Back in phase 2, we created the SMACSS (or equivalent) categories within the stylesheet. It’s now time to take it a step further and split those sections into separate CSS files: base.css, layout.css, module.css, state.css and theme.css.

I have to admit that I am not personally a fan of separate files, as I dislike hunting around in multiple places for the styles I need. However, this practice is useful if you spend a lot of time scrolling through an incredibly long stylesheet.

Make a Plan for @media

In planning ahead for responsive design, SMACSS has another good recommendation on how to manage @media queries. Instead of grouping them at the end of the stylesheet, as is typically done, Snook suggests adding the media queries to the layout and modules styles that they affect, placing the media queries around the module (or layout) states.

Yes, the media query declaration will most likely be declared multiple times, but all of the module information is kept together, which allows for testing the module by itself. And, if you have followed the earlier recommendation, the module styles will be in a separate file (module.css) anyway, so you won’t have to hunt through a huge CSS file to find them.

Phase 4: Sharing Is Caring

The final phase of the CSS optimization and scaling methodologies (notably from CSS for Grownups) in the MetaCoax process is to create a style-module library (also called a pattern library) and a Web site style guide. A pattern library is a repository of all the various modules and components by themselves. In contrast, a style guide is a document that illustrates the proper use of each of the components in the context of the entire Web site and how the components work together.

This style guide should encompass all the elements that can be found on the pages of your site and all of their corresponding styles. The initial page elements will not be tied to page layout, but will instead work independently within the context of a general page. The layout elements will then be added later, and the components tested to work inside the pieces of a page. The purpose of creating the two is to foster more consistency for your site moving forward.

While this is the “final” phase of the project, it really isn’t done last. Start early in the project. The pattern library and the accompanying style guide should not be tacked on to the end of the project as an afterthought – they are essential components of the CSS code-refactoring process.

Here’s what we are going to do:

Create a pattern library

Create a Web site style guide

Pattern Libraries

Building the pattern library is the method by which you can create the test cases for the styles in a completely neutral environment. Creating the pattern library should be done simultaneously as adjustments are made to the code. Here are some suggestions to get you started on building the pattern library for your site’s shiny new CSS:

Determine the unique elements and components that will be in the site. Also note the main colors for text, header, links, and buttons.

Style the modules/components of the pages independently of the page that they will live on to make the page truly modular.

Style the components that override the base styles, such as search boxes, breadcrumb navigation, themed buttons, and variations in modules. Include interaction styles: hover, focus, and active states.

Input all of the code and style snippets into a tool where the patterns are easy to access and manage.

As part of the refactoring process, you’ll be doing steps 1 through 3 anyway. The tricky part of creating the pattern library is figuring out how to structure it. There are great examples on the Web for inspiration and emulation. The MailChimp UI Pattern Library is a great example of a single-page pattern library. PatternPrimer is a great example of creating the code snippets independently of page layout context (also found on GitHub) and is especially geared for mobile first responsive design. The Pears Pattern tool is a like a mini pattern-library CMS built with WordPress to input and manage common patterns of markup and styles in a repository of all styles independent of context.

Web Site Style Guides

Now that you have the components of the Web site, it’s time to create the style guide that illustrates how everything works together within the context of the entire site, and not just on a page-by-page basis. By creating a style guide with the styles captured in the pattern library, you’ll break the tragic cycle that has befallen many a site, with CSS developed by many people who had no idea what the previous developers did with no documentation to go by.

However, it’s important to beware of some of the potential problems with style guides. They should not be too rigid, like traditional graphics-standards manuals, which frequently stifle creativity and encourage useless bureaucracy. Style guides need to be living, breathing entities and are actually part of the process of determining which styles are modules and can stand alone, irrespective of location on the page. The style guide should be the touch point between the design team and the development team of a site.

It can’t be stressed enough: the surefire way to ensure that creating a style guide is not Another Onerous Thing To Do is to create it while you are revamping the styles on the site. Following on the heels of creating the pattern library, in the article Front End Style Guides, Anna Debenham suggests these final steps for creating a style guide for your site:

Add layout last and put the components into place. Each layout could be presented as a separate document.

Encourage participation by the team and all of the front-end developers to ensure total brainshare.

Pro tip: Keep the style guide as short and sweet as possible, like this brand assets guide from MailChimp. No need to write a tome – the longer the style guide is, the lower the chance of anyone reading it, much less using it and then following the guidelines.

With the style guide in place, gone will be the days when styles weren’t documented while the site was being built, leaving each developer to figure out how to achieve the same styles on their own. It’s true that for large sites with many different layout options, a style guide will be a huge effort. But it will be well worth it in the end for the ease that it will lend to the site’s developers in the future.

MetaCoax Success

Theories that grow around processes are great intellectual exercises, but the best ideas are those that one can put to use. I developed the MetaCoax process by combining the best practices of several systems and put the process to the test with a Web site that had 7,500 lines of insanely bloated CSS code. How did the MetaCoax process do?

Instituted a grid, eliminating 327 instances of width and 738 instances of margin

Also eliminated the following:

1259 instances of div# and 836 instances of div

936 styles that contained body#

126 instances of !important

189 instances of margin-top and 112 instances of margin-bottom

Made the site’s code more future friendly

And…all of this was accomplished with no easily detectable visual change to the site!

Scalable and Modular CSS FTW!

So, there you have it: principles, practices and a process to give your CSS a revamp that will not only help you but also your development team—and will potentially change the workflow of your entire Web department for the better. Even if you don’t follow the process, I hope you now have the courage to look any CSS updating project in the eye with a newfound confidence on how to go about it. So, go forth, my friends, and get your CSS refactoring on!