Refactoring CSS: Introduction (Half 1)

No Comments

CSS is an easy stylesheet language for outlining a web site or doc’s presentation. Nevertheless, this simplicity leaves the door open for a lot of potential points and technical debt — bloated code, specificity hell, duplicated code blocks with little or no to no distinction, leftover unused selectors, pointless hacks, and workarounds, to call just a few. That sort of technical debt, if not paid on time, can accumulate and result in extreme points down the road. Mostly, it could result in sudden side-effects when including new UI parts and making the codebase troublesome to take care of. You’ve most likely labored on a undertaking with a poor CSS codebase earlier than and thought the way you’d written the code in another way, given the chance to refactor or rewrite all the pieces from scratch.

Refactoring giant elements of CSS code will not be a straightforward process by any measure. At occasions, it might appear that it’s only a case of “deleting the poor high quality code, writing higher CSS, and deploying the shiny improved code”. Nevertheless, there are numerous different components to think about, like the problem of refactoring a stay codebase, anticipated length and crew utilization, establishing refactoring targets, monitoring refactor effectiveness and progress, and so forth. There may be additionally the matter of convincing the administration or undertaking stakeholders to take a position the time and assets into the refactoring course of.

On this three-part sequence, we’re going to undergo the CSS refactor course of from the start to the top, beginning with data on strategy it and a few normal execs and cons of refactoring, then transferring onto the refactoring methods themselves and ending with some normal finest practices on CSS file dimension and efficiency.

Aspect-Results Of Poor-High quality CSS

For all its flexibility and ease, CSS itself has some elementary points that enable builders to write down poor-quality code within the first place. These points originate from its specificity and inheritance mechanisms, working in world scope, supply order dependency, and so forth. On a team-level degree, many of the CSS codebase points often originate from the various talent ranges and CSS data, totally different preferences and code types, lack of know-how of the undertaking construction and present code and parts, absence of project-level or team-level requirements and pointers, and so forth.

Consequently, poor-quality CSS could cause points that transcend the straightforward visible bugs and might produce numerous extreme side-effects that may have an effect on the undertaking as an entire. Some such examples embrace:

Reducing code high quality as extra options are added because of the various CSS talent ranges inside a improvement crew and missing inner guidelines, conventions, and finest practices.
Including new options or extending present selectors causes bugs and sudden side-effects in different elements of the code (also called a regression).
A number of totally different CSS selectors with duplicated code blocks or chunks of CSS code could be separated into a brand new selector and prolonged by variation.
Leftover, unused chunks of code from deleted options. The event crew has misplaced observe of which CSS code is used and which could be safely eliminated.
Inconsistency within the file construction, CSS class naming, total high quality of CSS, and so forth.
“Specificity hell” the place new options are added by overriding as an alternative of present the CSS codebase.
Undoing CSS the place higher-specificity selectors “reset” the lower-specificity selector fashion. Builders are writing extra code to have much less styling. This ends in redundancy and loads of waste in code.

In worst-case eventualities, all aforementioned points mixed may end up in a giant CSS file dimension, even with the CSS minification utilized. This CSS is often render-blocking, so the browser received’t even render the web site content material till it has completed downloading and parsing the CSS file, leading to a poor UX and efficiency on slower or unreliable networks.

These points not solely have an effect on the end-user but in addition the event crew and undertaking stakeholders by making the upkeep and have improvement troublesome, time-consuming and dear. This is without doubt one of the extra helpful arguments to deliver up when arguing for CSS refactor or rewrite.

The crew at Netlify famous that the explanation behind their large-scale CSS refactoring undertaking was the lowering code high quality and maintainability because the undertaking grew in complexity with increasingly UI parts added. They’ve additionally observed that the dearth of inner CSS requirements and documentation led to the lowering code high quality as increasingly folks have been engaged on the CSS codebase.

“(…) what began with organized PostCSS steadily grew to develop into a posh and entangled world CSS structure with loads of specificities and overrides. As you would possibly count on, there’s some extent the place the added tech debt it introduces makes it troublesome to maintain delivery quick with out including any regressions. Moreover, because the variety of frontend builders contributing to the codebase additionally grows, this type of CSS structure turns into much more troublesome to work with.”

Refactor Or Rewrite?

Refactoring permits builders to steadily and strategically enhance to the present codebase, with out altering its presentation or core performance. These enhancements are often small in scope and restricted, and don’t introduce breaking, wide-ranging architectural adjustments or add new conduct, options, or performance to the present codebase.

For instance, the present codebase options two variations of a card part — the primary one was applied early in undertaking improvement by an skilled developer and the second was added someday after the undertaking was launched by a much less skilled developer on a brief deadline, so it options duplicated code and wide-ranging selectors with high-specificity. A 3rd card variation must be added, which shares some types from the opposite two card variations. So to be able to keep away from bugs, duplicated code and complicated CSS courses, and HTML markup down the road, the crew decides to refactor the cardboard part CSS earlier than implementing a brand new variation.

Rewriting permits builders to make substantial adjustments to the codebase and assumes that almost all if not all code from the present codebase can be modified or changed. Rewrite permits builders to construct the brand new codebase from scratch, sort out core points from the present codebase that have been unimaginable or costly to repair, enhance the tech stack and structure and set up new inner guidelines and finest practices for the brand new codebase.

For instance, the shopper is in means of rebranding and the web site must be up to date with a brand new design and revamped content material. Since it is a site-wide change out of the field, builders determine to start out from scratch, rewrite the undertaking, and take this chance to handle the core points present CSS codebase has however can’t be solved with code refactor, replace the CSS tech stack, use the most recent instruments and options, set up new inner guidelines and finest practices for styling, and so forth.

Let’s summarize the professionals and cons of every strategy.

Refactor
Rewrite

Professionals

Incremental and versatile course of
Working with a single codebase
The crew will not be locked by the refactor duties
Simpler to persuade the stakeholder and undertaking leaders to do a refactor

Can tackle core points; outdated tech stack, naming conventions, architectural choices, inner guidelines, and so forth.
Impartial from the present codebase (present options and weaknesses…)
Lengthy-term plans for the codebase extensibility and maintainability

Cons

Depends upon the present codebase and core structure
Can’t tackle core points
Architectural choices, present inner guidelines and finest practices, wide-ranging points, and so forth.
Could also be sophisticated to execute, relying on the undertaking setup and codebase well being

Costly and time-consuming
Must be absolutely applied earlier than launch
Sustaining the present codebase whereas creating new codebase
Tougher to persuade the stakeholders and undertaking leaders to do a whole rewrite

|

When To Refactor CSS?

Refactoring is a advisable strategy for incrementally enhancing the CSS codebase whereas sustaining the present feel and appear (design). Staff members can work on addressing these codebase points when there aren’t any larger precedence duties. By incrementally enhancing the present codebase consumer expertise won’t be affected straight generally, nonetheless, a cleaner and extra maintainable codebase will lead to simpler characteristic implementation and fewer sudden bugs and side-effects. Undertaking stakeholders will most likely agree to take a position restricted time and assets into refactoring, however they’ll count on these duties to be executed shortly and can count on the crew to be obtainable for the first duties.

Refactoring CSS must be executed at common intervals when no wide-ranging design or content material adjustments aren’t deliberate for the close to future. Groups ought to proactively search the beforehand talked about weak factors within the present CSS codebase and work on addressing them each time there aren’t larger precedence duties obtainable. Lead frontend developer or the developer with essentially the most expertise with CSS ought to elevate points and create refactor duties to implement CSS code high quality requirements within the codebase.

When To Rewrite The CSS?

Rewriting the whole CSS codebase must be executed when the CSS codebase has core points that can not be addressed with refactoring or when refactoring is a dearer choice. Talking from private expertise, once I’ve began working for shoppers that moved from one other firm and the aforementioned CSS points and it was apparent that it’ll be a troublesome job to refactor, I’d begin by recommending a full rewrite and see what the shopper thinks. Most often, these shoppers have been dissatisfied with the state of the codebase and have been completely happy to proceed with the rewrite.

Another excuse for full CSS rewrite is when a considerable change is deliberate for the web site — rebranding, redesign, or every other vital change that impacts many of the web site. It’s secure to imagine that the undertaking stakeholders are conscious that it is a vital funding and it’ll take a while for the rewrite to be full.

Auditing CSS Codebase Well being

When the event crew has agreed on the truth that CSS code must be refactored to both streamline the characteristic improvement workflow or remove sudden CSS side-effects and bugs, the crew must deliver this suggestion as much as the undertaking stakeholders or a undertaking supervisor. It’s a good suggestion to offer some arduous knowledge alongside the subjective ideas on the codebase and the overall code evaluate. This may also give the crew a measurable objective that they are often conscious of whereas engaged on the refactor — goal file dimension, selector specificity, CSS code complexity, variety of media queries…

When doing a CSS audit or getting ready for a CSS refactor, I depend on a number of of many helpful instruments to get a normal overview and helpful stats concerning the CSS codebase.

My private go-to device is CSS Stats, s a free device that gives a helpful overview of the CSS codebase high quality with a number of helpful metrics that may assist builders catch some hard-to-spot points.

Again in 2016, trivago has executed a large-scale refactor for his or her CSS codebase and used the metrics from CSS Stats to set some concrete, measurable targets like lowering specificity and lowering the variety of coloration variations. In simply three weeks, they’ve managed to enhance the general well being of the CSS codebase, cut back the CSS file dimension, enhance render efficiency on cell, and so forth.

“A device like CSS Stats can simply assist you determine consistency points inside your codebase. Indicating what can occur when everyone has totally different opinions on how a gray tone ought to appear to be, you’ll find yourself with 50 shades of gray. Furthermore, Specificity Graph offers you total indication of your CSS base’s well being.”

As for CLI instruments, Wallace is a helpful device that gives considerably fundamental, however helpful CSS stats and overview which can be utilized to establish points associated to file dimension, variety of guidelines and selectors, selector sorts and complexity, and so forth.

Wallace additionally presents a free analyzer device on the Undertaking Wallace Web site which makes use of a seemingly extra superior model of Wallace within the backend to offer some helpful knowledge visualizations and few extra metrics that aren’t obtainable within the Wallace CLI.

Undertaking Wallace additionally presents a whole paid resolution for CSS codebase analytics. It options much more helpful options and metrics that may assist builders catch some hard-to-spot points and hold observe of CSS stats adjustments on a per-commit foundation. Though the paid plan contains extra options, the free plan, and the fundamental CSS analyzer device are greater than sufficient for auditing the CSS codebase high quality and getting a normal overview to make plans for refactoring.

Writing Excessive-High quality CSS

We’ve seen how the simplicity and adaptability of the CSS codebase could cause loads of points with code high quality, efficiency, and visible bugs. There isn’t a silver-bullet computerized device that may ensure that we write CSS in the absolute best manner and keep away from all doable architectural pitfalls alongside the best way.

The perfect instruments that may make sure that we write high-quality CSS code are self-discipline, consideration to element, and normal CSS data and skillset. Developer must be continuously conscious of the larger image and perceive what position their CSS performs in that larger image.

For instance, by overspecifying selectors, a single developer can severely restrict the usability, resulting in different builders having to duplicate the code to be able to use it for different, related parts with totally different markup. These points usually happen when builders lack understanding and never leveraging the underlying mechanisms behind CSS (cascade, inheritance, browser efficiency, and selector specificity). These early choices can result in main repercussions sooner or later, so the CSS codebase’s well being and maintainability relaxation on the developer’s data, abilities, and understanding of the CSS fundamentals.

Automated instruments will not be conscious of the larger image or how the selector is used, so they can not make these essential architectural choices, in addition to imposing some fundamental, predictable, and inflexible guidelines.

Talking from private expertise, I’ve discovered the next helped me to considerably enhance how I labored with CSS:

Studying the architectural patterns.
CSS Tips present an excellent data base and finest practices for writing high-quality CSS primarily based on normal programming patterns and architectural ideas.
Observe and enhance.
Work on private tasks or sort out a problem from Frontend Mentor to enhance your abilities. Begin with easy tasks (a single part or a bit) and give attention to writing the most effective CSS you’ll be able to, check out numerous approaches, apply numerous architectural patterns, steadily enhance the code, and learn to write high-quality CSS effectively.
Studying from errors.
Belief me, you’ll write some actually poor-quality CSS when you find yourself beginning out. It’ll take you just a few tries to get it proper. Take a second and take into consideration what went unsuitable, analyze the weak spots, take into consideration what you may have executed in another way and the way, and attempt to keep away from the identical errors sooner or later.

It’s additionally essential to set up guidelines and inner CSS requirements inside a crew and even for the entire firm. Clearly outlined company-wide requirements, code fashion, and ideas can yield many advantages corresponding to:

Unified and constant code fashion and high quality
Simpler to grasp, sturdy codebase
Streamlined undertaking onboarding
Standardized code evaluations that may be executed by any crew member, not simply the lead frontend developer or the extra skilled builders

Kirby Yardley has labored on refactoring the Sundance Institute design system and CSS and has identified the significance of creating inner guidelines and finest practices.

“With out correct guidelines and technique, CSS is a language that lends itself to misuse. Usually builders will write types particular to 1 part with out pondering critically about how that code could possibly be reused throughout different parts (…) After a number of analysis and deliberation about how we wished to strategy architecting our CSS, we determined to make use of a strategy known as ITCSS.“

Going again to the earlier instance from the crew at trivago, establishing inner guidelines and pointers proved to be an essential step for his or her refactoring course of.

“We launched a sample library, began using atomic design in our workflow, created new coding pointers, and tailored a number of methodologies like BEM and ITCSS to be able to help us in sustaining and creating our CSS/UI on a big scale.”

Not all guidelines and requirements should be manually checked and enforced. CSS linting instruments like Stylelint present some helpful guidelines that may allow you to examine for errors and implement inner requirements and customary CSS finest practices like disallowing empty CSS code blocks and feedback, disallowing duplicate selectors, limiting items, setting selector most specificity and nesting depth, establishing selector title sample, and so forth.

Conclusion

Earlier than deciding to suggest a granular codebase refactor or a full CSS rewrite, we have to perceive the problems with the present codebase so we will keep away from them sooner or later and have measurable knowledge for the method. CSS codebase could comprise a number of complicated high-specificity selectors which trigger sudden side-effects and bugs when including new options, possibly the codebase is affected by a number of repeated code chunks that may be moved right into a separate utility class, or possibly the combo of varied media queries are inflicting some sudden conflicts.

Helpful instruments like CSS Stats and Wallace can present a normal high-level overview of the CSS codebase and provides an in depth perception into codebase state and well being. These instruments additionally present measurable stats that can be utilized for setting the targets for the refactoring course of and hold observe of the refactoring progress.

After figuring out refactoring targets and scope, it’s essential to set inner pointers and finest practices for CSS codebase — naming conference, architectural ideas, file, and folder construction, and so forth. This ensures code consistency, establishes a core basis throughout the undertaking which could be documented and which can be utilized for onboarding and CSS code evaluate. Utilizing linting instruments like Stylelint may also help to implement some widespread CSS finest practices to partially automate the code evaluate course of.

Within the subsequent article from this three-part sequence, we’re going to dive right into a bulletproof CSS refactoring technique which ensures a seamless transition between the present codebase and refactored codebase.

References

Managing CSS Initiatives With ITCSS,” Harry Roberts
Giant Scale CSS Refactoring At Trivago,” Christoph Reinartz
Sundance.org Design System And CSS Refactor,” Kirby Yardley
From Semantic CSS To Tailwind: Refactoring The Netlify UI Codebase,” Charlie Gerard & Leslie Cohn-Wein
CSS Auditing Instruments,” Iris Lješnjanin

    About Marketing Solution Australia

    We are a digital marketing company with a focus on helping our customers achieve great results across several key areas.

    Request a free quote

    We offer professional SEO services that help websites increase their organic search score drastically in order to compete for the highest rankings even when it comes to highly competitive keywords.

    Subscribe to our newsletter!

    More from our blog

    See all posts

    Leave a Comment