Many 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 条规则,1 个声明=> 内聚性= 1 */ .text-center { text-align: center; } /* 1 条规则,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 将删除任何后续规则"selectors.total": 4095, // 我们不需要ID 选择器"selectors.id.total": 0, // 如果出现除这些颜色之外的任何其他颜色,则报告错误! "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!

Linking CSS files to HTML can be achieved by using elements in part of HTML. 1) Use tags to link local CSS files. 2) Multiple CSS files can be implemented by adding multiple tags. 3) External CSS files use absolute URL links, such as. 4) Ensure the correct use of file paths and CSS file loading order, and optimize performance can use CSS preprocessor to merge files.

Choosing Flexbox or Grid depends on the layout requirements: 1) Flexbox is suitable for one-dimensional layouts, such as navigation bar; 2) Grid is suitable for two-dimensional layouts, such as magazine layouts. The two can be used in the project to improve the layout effect.

The best way to include CSS files is to use tags to introduce external CSS files in the HTML part. 1. Use tags to introduce external CSS files, such as. 2. For small adjustments, inline CSS can be used, but should be used with caution. 3. Large projects can use CSS preprocessors such as Sass or Less to import other CSS files through @import. 4. For performance, CSS files should be merged and CDN should be used, and compressed using tools such as CSSNano.

Yes,youshouldlearnbothFlexboxandGrid.1)Flexboxisidealforone-dimensional,flexiblelayoutslikenavigationmenus.2)Gridexcelsintwo-dimensional,complexdesignssuchasmagazinelayouts.3)Combiningbothenhanceslayoutflexibilityandresponsiveness,allowingforstructur

What does it look like to refactor your own code? John Rhea picks apart an old CSS animation he wrote and walks through the thought process of optimizing it.

CSSanimationsarenotinherentlyhardbutrequirepracticeandunderstandingofCSSpropertiesandtimingfunctions.1)Startwithsimpleanimationslikescalingabuttononhoverusingkeyframes.2)Useeasingfunctionslikecubic-bezierfornaturaleffects,suchasabounceanimation.3)For

@keyframesispopularduetoitsversatilityandpowerincreatingsmoothCSSanimations.Keytricksinclude:1)Definingsmoothtransitionsbetweenstates,2)Animatingmultiplepropertiessimultaneously,3)Usingvendorprefixesforbrowsercompatibility,4)CombiningwithJavaScriptfo

CSSCountersareusedtomanageautomaticnumberinginwebdesigns.1)Theycanbeusedfortablesofcontents,listitems,andcustomnumbering.2)Advancedusesincludenestednumberingsystems.3)Challengesincludebrowsercompatibilityandperformanceissues.4)Creativeusesinvolvecust


Hot AI Tools

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

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

Undress AI Tool
Undress images for free

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

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

Atom editor mac version download
The most popular open source editor

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.
