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.
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.
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 https://www.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 https://www.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:
- CSS Debugging and Optimization: Browser-based Developer Tools
- CSS Debugging and Optimization: Minification with CSSO
Frequently Asked Questions (FAQs) on CSS Debugging and Optimization Code Quality Tools
What are the benefits of using CSS debugging and optimization code quality tools?
CSS debugging and optimization code quality tools are essential for any web developer. They help in identifying and fixing errors in your CSS code, ensuring that your website functions as intended. These tools also help in optimizing your CSS code, which can significantly improve your website’s loading speed. This is crucial as a slow-loading website can lead to a poor user experience and negatively impact your website’s search engine ranking. Additionally, these tools can help in maintaining the quality of your CSS code, making it easier to read and manage.
How does UnCSS work?
UnCSS is a powerful tool that analyzes your HTML and CSS files to remove unused styles. It works by parsing your HTML files, identifying the CSS selectors used, and then comparing them with the selectors in your CSS files. Any selector in your CSS files that is not used in your HTML files is considered unused and is removed. This can significantly reduce the size of your CSS files, leading to faster loading times for your website.
How can I use UnCSS online?
UnCSS online is a web-based tool that allows you to use UnCSS without having to install it on your computer. To use it, simply go to the UnCSS online website, paste your HTML and CSS code into the provided fields, and click the “Remove unused CSS” button. The tool will then analyze your code and provide you with a new CSS file that only contains the styles used in your HTML code.
Are there any video tutorials on how to use UnCSS?
Yes, there are several video tutorials available online that can guide you on how to use UnCSS. These tutorials provide step-by-step instructions, making it easy for even beginners to understand and use the tool. One such tutorial is available on YouTube.
How can I remove unused CSS from my website?
There are several tools and methods available for removing unused CSS from your website. One of the most popular tools is UnCSS, which analyzes your HTML and CSS files to remove unused styles. Other tools include PurifyCSS and CSSNano, which also help in optimizing your CSS code. Additionally, you can manually remove unused CSS by inspecting your website using browser developer tools and identifying the unused styles.
What are some other CSS debugging and optimization tools?
Apart from UnCSS, there are several other CSS debugging and optimization tools available. These include CSS Lint, which helps in identifying and fixing errors in your CSS code; CSS Minifier, which reduces the size of your CSS files by removing unnecessary characters; and Autoprefixer, which adds vendor prefixes to your CSS to ensure compatibility with different browsers.
How can I ensure the quality of my CSS code?
Ensuring the quality of your CSS code involves several practices. These include using a CSS preprocessor like Sass or Less, which can help in organizing your code and making it easier to manage; using a CSS linter to identify and fix errors; and using a CSS optimizer to remove unnecessary characters and optimize your code. Additionally, following best practices like using meaningful class and id names, commenting your code, and adhering to a consistent coding style can also help in maintaining the quality of your CSS code.
How can CSS debugging and optimization tools improve my website’s SEO?
CSS debugging and optimization tools can significantly improve your website’s SEO by improving its loading speed. Search engines like Google consider page loading speed as a ranking factor, so a faster-loading website can potentially rank higher in search results. Additionally, these tools can help in creating a better user experience, which can also positively impact your website’s SEO.
Can I use CSS debugging and optimization tools if I’m a beginner?
Yes, most CSS debugging and optimization tools are designed to be user-friendly and can be used by both beginners and experienced developers. Many of these tools provide detailed documentation and tutorials to help you get started. However, it’s important to have a basic understanding of CSS before using these tools.
Are there any drawbacks to using CSS debugging and optimization tools?
While CSS debugging and optimization tools offer many benefits, they also have some potential drawbacks. For instance, some tools may remove styles that are not currently used but may be needed in the future. Additionally, these tools may sometimes produce false positives, identifying styles as unused when they are actually needed. Therefore, it’s important to thoroughly review the changes made by these tools before implementing them on your website.
Tiffany B. Brown is a freelance web developer and technical writer based in Los Angeles. Brown offers web development and consulting services to larger agencies and small businesses. A former member of the Opera Software developer relations team, Brown is also co-author of SitePoint's JumpStart HTML5 book. She sporadically writes about web development technology on her blog. You can follow her on Twitter at @webinista.