


In Search of a Stack That Monitors the Quality and Complexity of CSS
Apr 18, 2025 am 11:22 AMMany developers write about how to maintain a CSS code base, but few people write about how they measure the quality of the code base. Of course, we have excellent code checking tools like StyleLint and CSSLint, but they can only prevent errors at the micro level. Use wrong color notation, add vendor prefixes when Autoprefixer is already used, write selectors in an inconsistent way...etc.
We are always looking for ways to improve how CSS is written: OOCSS, BEM, SMACSS, ITCSS, Practical First, and more. But other development communities seem to have evolved from simple code checking tools to tools like SonarQube and PHP Mess Detector, while the CSS community still lacks more in-depth checking tools than shallow lint rules. To do this, I created Project Wallace, a set of tools for checking and enforcing CSS quality.
What is Project Wallace?
At the heart of Project Wallace is a set of tools, including a command line interface, a code inspector, an analyzer, and a reporter.
Here is a brief overview of these tools.
Command line interface
This allows you to run CSS analysis on the command line and get statistics for any CSS you provide to it.
Constyble Code Checker
This is a code checker designed specifically for CSS. Based on the analysis results generated by Wallace, you can set thresholds that should not be exceeded. For example, a single CSS rule should not contain more than 10 selectors, or the average selector complexity should not be higher than 3.
Analyzer
Extract-CSS As its name suggests: Extract all CSS from a webpage so that we can send it to projectwallace.com for analysis.
Reporter
All analysis results for Extract CSS are sent to projectwallace.com, and the dashboard contains reports of all data. It's similar to CSS Stats, but it tracks more metrics and stores results over time and displays them in the dashboard. It also shows the difference between the two time points, as well as many other features.
Analyze CSS complexity
There are not many articles about CSS complexity, but the one Harry Roberts (csswizardry) wrote impressed me. The point is that each CSS selector is basically a bunch of if statements, which reminds me of the loop complexity of the method I had to manually calculate when taking a computer science course. Harry's article makes a lot of sense to me because it can write a module to calculate the complexity of a CSS selector - not to be confused with specificity, of course, because it's a completely different question in terms of complexity.
Basically, complexity in CSS can come in many forms, but here are a few of the things I pay most attention to when reviewing codebases:
CSS selector loop complexity
Each part of the selector means that the browser needs to execute another if statement. Longer selectors are more complex than shorter selectors. They are harder to debug, and browser parsing is slower and harder to cover.
<code>.my-selector {} /* 1 個標識符*/ .my #super [complex^="selector"] > with ~ many :identifiers {} /* 6 個標識符*/</code>
Number of declarations per rule set (cohesion)
Rule sets containing many declarations are more complex than rule sets containing a small number of declarations. The popularity of functional CSS frameworks such as Tailwind and Tachyons may be attributed to the relative "simplicity" of CSS itself.
<code>/* 1 條規(guī)則,1 個聲明=> 內聚性= 1 */ .text-center { text-align: center; } /* 1 條規(guī)則,8 個聲明=> 內聚性= (1 / 8) = 0.125 */ .button { background-color: blue; color: white; padding: 1em; border: 1px solid; display: inline-block; font-size: normal; font-weight: bold; text-decoration: none; }</code>
Number of source code lines
The more code, the more complexity. Each line of code is maintained and is therefore included in the report.
Average number of selectors per rule
A rule usually contains 1 selector, but sometimes more. This makes it difficult to delete some parts of the CSS, making it more complicated.
All of these metrics can be code-checked using Constyble, the CSS complexity code checker used by Project Wallace in its tool set. After defining the baseline for the metric, just install Constyble and set up the configuration file. Here is an example of the configuration file I extracted directly from the Constyble Readme:
<code>{ // 不要超過4095 個選擇器,否則IE9 將刪除任何后續(xù)規(guī)則"selectors.total": 4095, // 我們不需要ID 選擇器"selectors.id.total": 0, // 如果出現(xiàn)除這些顏色之外的任何其他顏色,則報告錯誤! "values.colors.unique": ["#fff", "#000"] }</code>
The best part is that Constyble runs on your final CSS, so it only performs its operations after all the preprocessing work you have from Sass, Less, PostCSS, or any other preprocessor you use. This way we can do a smart check of the total number of selectors or the average selector complexity – just like any code inspector, you can use it as part of the build step and if any issues arise, your build will fail.
The harvest of using Project Wallace
After using Project Wallace for a while, I found it to be great for tracking complexity. While it is mainly used for this purpose, it is also a good way to find subtle errors that code inspectors in CSS may not find, as they are checking for preprocessed code. Here are some interesting things I found:
- I've stopped counting the number of user stories that need to fix inconsistent colors on the site during the sprint. There have been projects for several years, and people coming in and out of the company: This is a secret to making every brand color on the website go wrong. Fortunately, we implemented Constyble and Project Wallace to gain stakeholder recognition as we were able to prove that our clients’ brand was very accurate in new projects. Constyble prevents us from adding colors that are not in the style guide.
- I have installed Project Wallace webhooks in a project where my former employer works. Any time you add a new CSS to your project, it will send the CSS to projectwallace.com and will be displayed immediately in the project's dashboard. This makes it easy to find when a specific selector or media query is added to the CSS.
- The CSS-Tricks redesign earlier this year meant a significant drop in complexity and file size. The redesign is great and can be analyzed. It gives you the opportunity to take a closer look at the situation behind the scenes and figure out how the authors have changed their CSS. Knowing which sections do not work for the site and which new sections apply may give you an idea of ??how fast CSS is growing.
- A large international company based in the Netherlands once had more than 4095 selectors in a CSS file. I know they are actively developing emerging markets and they have to support Internet Explorer 8. IE9 stops reading all CSS after 4095 selectors, so most of their CSS is not applied in older IE browsers. I sent them an email and they verified the issue and immediately fixed it by splitting the CSS into two files.
- GitLab currently uses over 70 unique font sizes. I'm pretty sure their typography is complicated, but this seems a bit too ambitious. Maybe it's because of some third-party CSS, but it's hard to judge.
- When inheriting projects from other developers, I review the CSS analysis results to understand the difficulties of the project. Are they using it in large quantities!important? Is the average rule set size easy to understand, or do they add more than 20 declarations per rule set? What is the average selector length and are they difficult to cover? It would be nice not to resort to .complex-selector-override\[class\][class]...[class].
- A clever trick to check whether the zoom-out is effective is to have Constyble check whether the line number indicator of the code is not greater than 1. CSS Shrinking means that all CSS is placed on one line, so the number of lines of code should be equal to 1!
- What happened all the time in my other project was the failure to shrink. I don't know until the difference in Project Wallace shows me a lot of colors suddenly get written out like #aaaaa instead of #aaaa. This isn't a bad thing in itself, but it happens in so many colors at the same time that something must have gone wrong. A quick survey showed that I made a mistake in shrinking.
- StackOverflow has four unique ways to write white colors. This is not necessarily a bad thing, but it can be a sign that CSS minification programs are corrupted or inconsistent in design systems.
- Facebook.com has over 650 unique colors in their CSS. The broken design system is also starting to sound like a possibility.
- A project from my former employer shows input[type=checkbox]:checked .label input[type=radio] label:focus:after is the most complex selector. After a closer inspection, we found that this selector locates inputs nested in another input. This is impossible in HTML, and we think we must have forgotten the comma in CSS. No code checker warns us about this.
- Nesting in CSS preprocessors is cool, but can cause wrong things like @media (max-width: 670px) and (max-width: 670px), as I found in Syntax.fm.
For Project Wallace, this is just the tip of the iceberg. Once you start analyzing your CSS, there is more to learn and discover. Don't just look at your own statistics, but also what others are doing.
I've used my Constyble configuration as a topic of conversation with less experienced developers to explain why they fail to build on complex CSS blocks. Discussing with other developers why we should avoid or promote certain CSS writing methods can help transfer knowledge. It also helps me to keep my feet on the ground. Having to explain to the PHP developers who just want to help, what I've done for years has made me rethink why I'm doing things the way I do.
My goal is not to tell anyone what is right or wrong in CSS, but to create tools so that you can verify what works for you and your colleagues. Project Wallace is here to help us understand the CSS we write.
The above is the detailed content of In Search of a Stack That Monitors the Quality and Complexity of CSS. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

There are three ways to create a CSS loading rotator: 1. Use the basic rotator of borders to achieve simple animation through HTML and CSS; 2. Use a custom rotator of multiple points to achieve the jump effect through different delay times; 3. Add a rotator in the button and switch classes through JavaScript to display the loading status. Each approach emphasizes the importance of design details such as color, size, accessibility and performance optimization to enhance the user experience.

To deal with CSS browser compatibility and prefix issues, you need to understand the differences in browser support and use vendor prefixes reasonably. 1. Understand common problems such as Flexbox and Grid support, position:sticky invalid, and animation performance is different; 2. Check CanIuse confirmation feature support status; 3. Correctly use -webkit-, -moz-, -ms-, -o- and other manufacturer prefixes; 4. It is recommended to use Autoprefixer to automatically add prefixes; 5. Install PostCSS and configure browserslist to specify the target browser; 6. Automatically handle compatibility during construction; 7. Modernizr detection features can be used for old projects; 8. No need to pursue consistency of all browsers,

Use the clip-path attribute of CSS to crop elements into custom shapes, such as triangles, circular notches, polygons, etc., without relying on pictures or SVGs. Its advantages include: 1. Supports a variety of basic shapes such as circle, ellipse, polygon, etc.; 2. Responsive adjustment and adaptable to mobile terminals; 3. Easy to animation, and can be combined with hover or JavaScript to achieve dynamic effects; 4. It does not affect the layout flow, and only crops the display area. Common usages are such as circular clip-path:circle (50pxatcenter) and triangle clip-path:polygon (50%0%, 100 0%, 0 0%). Notice

Themaindifferencesbetweendisplay:inline,block,andinline-blockinHTML/CSSarelayoutbehavior,spaceusage,andstylingcontrol.1.Inlineelementsflowwithtext,don’tstartonnewlines,ignorewidth/height,andonlyapplyhorizontalpadding/margins—idealforinlinetextstyling

Setting the style of links you have visited can improve the user experience, especially in content-intensive websites to help users navigate better. 1. Use CSS's: visited pseudo-class to define the style of the visited link, such as color changes; 2. Note that the browser only allows modification of some attributes due to privacy restrictions; 3. The color selection should be coordinated with the overall style to avoid abruptness; 4. The mobile terminal may not display this effect, and it is recommended to combine it with other visual prompts such as icon auxiliary logos.

To create responsive images using CSS, it can be mainly achieved through the following methods: 1. Use max-width:100% and height:auto to allow the image to adapt to the container width while maintaining the proportion; 2. Use HTML's srcset and sizes attributes to intelligently load the image sources adapted to different screens; 3. Use object-fit and object-position to control image cropping and focus display. Together, these methods ensure that the images are presented clearly and beautifully on different devices.

Different browsers have differences in CSS parsing, resulting in inconsistent display effects, mainly including the default style difference, box model calculation method, Flexbox and Grid layout support level, and inconsistent behavior of certain CSS attributes. 1. The default style processing is inconsistent. The solution is to use CSSReset or Normalize.css to unify the initial style; 2. The box model calculation method of the old version of IE is different. It is recommended to use box-sizing:border-box in a unified manner; 3. Flexbox and Grid perform differently in edge cases or in old versions. More tests and use Autoprefixer; 4. Some CSS attribute behaviors are inconsistent. CanIuse must be consulted and downgraded.

The choice of CSS units depends on design requirements and responsive requirements. 1.px is used for fixed size, suitable for precise control but lack of elasticity; 2.em is a relative unit, which is easily caused by the influence of the parent element, while rem is more stable based on the root element and is suitable for global scaling; 3.vw/vh is based on the viewport size, suitable for responsive design, but attention should be paid to the performance under extreme screens; 4. When choosing, it should be determined based on whether responsive adjustments, element hierarchy relationships and viewport dependence. Reasonable use can improve layout flexibility and maintenance.
