CSS Debugging and Optimization: Code-quality Tools

The following introduction to CSS code-quality tools is an extract from Tiffany’s new book, CSS Master, 2nd Edition.

On your road to becoming a CSS master, you’ll need to know how to troubleshoot and optimize your CSS. How do you diagnose and fix rendering problems? How do you ensure that your CSS creates no performance lags for end users? And how do you ensure code quality?

Knowing which tools to use will help you ensure that your front end works well.

--ADVERTISEMENT--

In this article, we’ll discuss tools that help you analyze the quality of your CSS. We’ll focus on two:

  • stylelint
  • UnCSS

stylelint is a linting tool. A linter is an application that checks code for potential trouble spots, enforcing coding conventions such as spaces instead of tabs for indentation. stylelint can find problems such as duplicate selectors, invalid rules, or unnecessary specificity. These have the greatest impact on CSS maintainability.

UnCSS, on the other hand, checks your CSS for unused selectors and style rules. It parses a stylesheet and a list of HTML pages, returning a CSS file that’s stripped of unused rules.

Both of these tools use Node.js and can be installed using npm.

If you’re working on a small site, such as a personal blog or a few pages that are updated infrequently, many of the problems that these tools flag can safely be ignored. You’ll spend time refactoring for little gain in maintainability and speed. For larger projects, however, they’re invaluable. They’ll help you head off maintainability problems before they start.

stylelint

stylelint helps you avoid errors and enforce conventions in your styles. It has more than 160 error-catching rules and allows you to create your own as well via plugins.

stylelint Installation and Configuration

Install stylelint as you would any other npm package:

npm install -g stylelint

Once it’s installed, we’ll need to configure stylelint before using it. stylelint doesn’t ship with a default configuration file. Instead, we need to create one. Create a .stylelistrc file in your project directory. This file will contain our configuration rules, which can use JSON (JavaScript Object Notation) or YAML (YAML Ain’t Markup Language) syntax. Examples in this section use JSON.

Our .stylelistrc file must contain an object that has a rules property. The value of rules will itself be an object containing a set of stylelist rules and their values:

{
    "rules": {}
}

If, for example, we wanted to banish !important from declarations, we can set the declaration-no-important to true:

{
    "rules": {
        "declaration-no-important": true
    }
}

stylelint supports over 150 rules that check for syntax errors, indentation and line-break consistency, invalid rules, and selector specificity. You’ll find a complete list of rules and their available values in the stylelint User Guide.

Starting with a Base stylelint Configuration

You’ll probably find it easier to start with a base configuration and then customize it to your project needs. The stylelint-config-recommended base configuration is a good starting configuration. It enables all of the “possible errors” rules. Install it using npm:

npm install -g stylelint-config-recommended

Then, in your project directory, create a .stylelistrc file that contains the following lines:

{
    "extends": "/absolute/path/to/stylelint-config-recommended"
}

Replace /absolute/path/to/ with the directory to which stylelint-config-recommended was installed. Global npm packages can usually be found in the %AppData%\npm\node_modules directory on Windows 10 systems, and in /usr/local/lib/node_modules on Unix/Linux and macOS systems. Type npm list -g to locate your global node_modules directory.

We can then augment our configuration by adding a rules property. For example, to disallow vendor prefixes, our .stylelistrc file would look similar to the what’s below:

{
    "extends": "/absolute/path/to/stylelint-config-recommended",
    "rules": {
       "value-no-vendor-prefix": true
    }
}

What if we wanted to limit the maximum specificity of our selectors to 0,2,0? That would permit selectors such as .sidebar .title but not #footer_nav. We can do this by adding a selector-max-specificity rule to our configuration:

{
    "extends": "/absolute/path/to/stylelint-config-recommended",
    "rules": {
       "value-no-vendor-prefix": true,
       "selector-max-specificity": "0,2,0"
    }
}

Using stylelint

To lint your CSS files using stylelint, run the stylelint command, passing the path to your CSS file as an argument:

stylelint stylesheet.css

Alternatively, you can lint all of the CSS files in a particular directory, even recursively:

stylelint "./css/**/*.css"

stylelint can also lint CSS that’s embedded in HTML files using the style element. Just pass the path to an HTML file as the argument.

When complete, stylelint will display a list of files that contain errors, along with their type and location, as shown in the image below.

Terminal output from stylelintTerminal output from stylelint

UnCSS

UnCSS parses your HTML and CSS files, removing unused CSS. If your projects include a CSS framework such as Bootstrap or use a reset stylesheet, consider adding UnCSS to your workflow. It will shave unnecessary CSS—and bytes—from your code.

UnCSS Installation

As with other npm packages, you can install UnCSS using the following command:

npm install -g uncss

Using UnCSS from the Command Line

UnCSS requires the file path or URL of an HTML page that contains a linked CSS file. For example:

uncss http://sitepoint.com/

UnCSS will parse the HTML and its linked stylesheets, and print the optimized CSS to standard output. To redirect to a file, use the redirect operator (>):

uncss http://sitepoint.com/ > optimized.css

You can also pass multiple file paths or URLs to the command line. UnCSS will analyze each file and dump optimized CSS that contains rules affecting one or more pages:

uncss index.html article-1.html article-2.html > optimized.css

For a full list of commands—and an example of how to use UnCSS with a Node.js script—consult the UnCSS docs.

Consider a Task Runner or Build Tool

Running these tools probably seems like a lot of extra work. To that end, consider adding a task runner or build system to your workflow. Popular ones include Grunt, Gulp, and webpack. All three have robust documentation and sizable developer communities.

What’s great about these task runners and build systems is that they automate concatenation and optimization tasks. They’re not limited to CSS either. Most build tools also include plugins for optimizing JavaScript and images.

Because the configuration and build script files are typically JSON and JavaScript, you can easily reuse them across projects or share them with a team. Each of the tools mentioned in this article can be integrated with Grunt, Gulp, or webpack with the help of a plugin.

Above all, however, take a pragmatic approach to building your toolkit. Add tools that you think will enhance your workflow and improve the quality of your output.

To read more on CSS debugging and optimization, check out Tiffany’s book, CSS Master, 2nd Edition.

Related articles: