


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 個聲明=> 內(nèi)聚性= 1 */ .text-center { text-align: center; } /* 1 條規(guī)則,8 個聲明=> 內(nèi)聚性= (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)

Hot Topics

CSS blocks page rendering because browsers view inline and external CSS as key resources by default, especially with imported stylesheets, header large amounts of inline CSS, and unoptimized media query styles. 1. Extract critical CSS and embed it into HTML; 2. Delay loading non-critical CSS through JavaScript; 3. Use media attributes to optimize loading such as print styles; 4. Compress and merge CSS to reduce requests. It is recommended to use tools to extract key CSS, combine rel="preload" asynchronous loading, and use media delayed loading reasonably to avoid excessive splitting and complex script control.

ThebestapproachforCSSdependsontheproject'sspecificneeds.Forlargerprojects,externalCSSisbetterduetomaintainabilityandreusability;forsmallerprojectsorsingle-pageapplications,internalCSSmightbemoresuitable.It'scrucialtobalanceprojectsize,performanceneed

No,CSSdoesnothavetobeinlowercase.However,usinglowercaseisrecommendedfor:1)Consistencyandreadability,2)Avoidingerrorsinrelatedtechnologies,3)Potentialperformancebenefits,and4)Improvedcollaborationwithinteams.

CSSismostlycase-insensitive,butURLsandfontfamilynamesarecase-sensitive.1)Propertiesandvalueslikecolor:red;arenotcase-sensitive.2)URLsmustmatchtheserver'scase,e.g.,/images/Logo.png.3)Fontfamilynameslike'OpenSans'mustbeexact.

Autoprefixer is a tool that automatically adds vendor prefixes to CSS attributes based on the target browser scope. 1. It solves the problem of manually maintaining prefixes with errors; 2. Work through the PostCSS plug-in form, parse CSS, analyze attributes that need to be prefixed, and generate code according to configuration; 3. The usage steps include installing plug-ins, setting browserslist, and enabling them in the build process; 4. Notes include not manually adding prefixes, keeping configuration updates, prefixes not all attributes, and it is recommended to use them with the preprocessor.

CSScounterscanautomaticallynumbersectionsandlists.1)Usecounter-resettoinitialize,counter-incrementtoincrease,andcounter()orcounters()todisplayvalues.2)CombinewithJavaScriptfordynamiccontenttoensureaccurateupdates.

In CSS, selector and attribute names are case-sensitive, while values, named colors, URLs, and custom attributes are case-sensitive. 1. The selector and attribute names are case-insensitive, such as background-color and background-Color are the same. 2. The hexadecimal color in the value is case-sensitive, but the named color is case-sensitive, such as red and Red is invalid. 3. URLs are case sensitive and may cause file loading problems. 4. Custom properties (variables) are case sensitive, and you need to pay attention to the consistency of case when using them.

Theconic-gradient()functioninCSScreatescirculargradientsthatrotatecolorstopsaroundacentralpoint.1.Itisidealforpiecharts,progressindicators,colorwheels,anddecorativebackgrounds.2.Itworksbydefiningcolorstopsatspecificangles,optionallystartingfromadefin
