How to clean up bad CSS


#1

What is the best way to begin tackling a web application with numerous stylesheets that have grown unwieldy and just generally out of control? Every time I need to edit or add a new style declaration, I just shake my head because the CSS is such a mess. It’s all somehow still “working” (or at least to the satisfaction of my client at this point). But they have a successful application that I’d hate to see become crippled due to poor CSS practices, which surely is inevitable if things continue like this. Multiple agencies and contractors have contributed to this growing disaster over 10+ years, but I’d really like to stop the madness and begin the process of cleaning things up. Is this best done in small steps? Or might it be better for me to create a copy of their application, strip out all the CSS and just start over from scratch? Not sure where to begin… I’d really appreciate any ideas.


#2

In my experience I have found it much faster and easier to start from scratch so I would say make a copy of the app and work on that.


#3

Here are a couple of basic tips that may ease CSS maintenance over time in complex projects:

  1. Keep your selectors simple: do not add unnecessary specificity to your rules as this will only make things more complicated once you have to override those rules. By specificity I mean the complexity of selectors. So instead of .listWrapper ul li a use .listWrapper a

  2. Whenever you are creating a new rule-set keep in mind what is the purpose and context of that rule-set and only add the properties that make sense for that scope and context. So you may decide to create 2 rule-sets… one that is global and another one that deals with the particular context of that element in a given scope.

  3. In order to override you base rules, It helps to add classes to the document body, which indicate the context of a particular page e.g. page-user-profile section-details user-type-basic


#4

Is the client willing to pay for your time and only have the web-pages look exactly the same?


#5

That’s a very good point John, and I think many web projects reach end of life too early because maintenance is not something that clients or managers like to factor into the budget or at all. The OP should definitely not attempt doing all that work without an understanding with the client first. The client should understand the benefits and be willing to pay for the work


#6

Thanks for fast responses from everyone. You guys are right to bring up my client paying for this… they have not yet approved any time for this work yet, but I am hoping to convince them that this would be a worthwhile project, given that the web application is an integral part of their business. However, I’m guessing that my recommendation to clean up the CSS will be appreciated but put on a shelf until it gets to a point it can no longer be ignored. But I wanted to at least try to get a sense of how I might go about tackling it, should they agree that it makes sense to begin addressing this sooner rather than later.

@Andres_Vaquero - thanks for the tips. I actually was wondering about #1. When creating a new stylesheet, I always struggle with how specific to make the rule selectors so I appreciate your recommendation to start with simple selectors. Likewise, #2 makes sense, as it sounds like you’re suggesting to avoid adding unnecessary rules to a rule set (keeping them simple), and to consider that it may actually make sense in some situations to add multiple rule sets, in situations where one rule set might be used globally throughout a website or application, whereas another ruleset might only need to be applied within a more limited scope. Is that right? Regarding #3, this is my biggest challenge with this particular project because I have no say-so over the coding of the application. I can probably make suggestions though, so I’ll keep this in mind as I go through the CSS (should my client eventually gives me the green light to work on the CSS!).


#7

Yes that’s it… One of the biggest problems in CSS is that you end up making it hard to override other rules and have to resort to unwieldy selectors or !important. Also if you don’t keep things semantic and in scope you will lose track of what is the purpose of each rule-set and the mess will have started.

Keep your files organised with comments that delimit the different sections of the file… group rule-sets into chunks of the same context within a file.

If you’re using pre-processors beware of code nesting… this leads to unnecessary specificity and also obscures the code.

About point number 3, I’m sure you can do without it but keep it in mind and if you find a clear case that would ease your job quite a lot, then you might suggest it to your client or whoever is in charge of that bit.


#8

When I first started creating CSS Stylesheets I was not happy because it seemed to go against the Dont Repeat Yourself Principal, DRY.

I realised the problem was going to rapidly escalate and took these steps to rewrite a stylesheet:

  1. ran the stylesheet through an online word count application.
  2. adjusted spaces and capitalisation
  3. re-checked
  4. noted the stylesheet file size
  5. selected a property such as background-color:snow;
  6. deleted all occurrences of background-color:snow;
  7. created new class rule .bgs {background-color:snow;}
  8. added class=“bgs” to the web page
  9. validated
  10. repeated all steps again until no duplicate property existed

Afterwards compared file sizes and surprised at the difference.

I adopted Three Letter Acronyms for subsequent stylesheets and added specific oddball classes where necessary,

Give it try, the results are often impressive.

Edit:
Note to Moderators, please correct any CSS names, rules, properties, etc if they are used incorrectly.


#9

We all have our coding styles and preferences, but I’m not too keen on this.

How is class="bgs" different from style="background-color:snow"? (Which is generally frowned upon)
One difference is, class="bgs" requires loading an external style sheet.

But on the “plus” side, if you re-branded and and wanted a gold background on your elements, you only need change it in one place, like this:-

.bgs{background-color:gold;}

Anyone see the problem?

While you adhere to the principles of DRY and slimming your code, which is commendable, it goes against the principles of separation of concerns and maintainability, which is the point of external CSS.

Another approach which can maintain class names which reflect the context of the element, rather than describing the styles applied to them, is to group selectors with common styles.

.header, .footer, .widget {background-color:snow;}

Though too much of this may lead to a fragmented style sheet, with for example the .header selector appearing several times at different points in the sheet with one rule at a time added to it.
Is repeating .header a lot better than repeating background-color:snow;?

An answer may be to have a “master” class to encompass all the three above elements, and that’s kind of what you did there.
But, I don’t know, some may disagree, and it’s just me. But I have a bit on an aversion to html elements with several classes (if I use 3 I feel dirty) and class names that describe the style too closely, particularly if it’s just tied to one style rule like this. It just looks to me like in-lining in a more abstract/cryptic form.
Granted, a hand full of “utility classes” are very useful and we all use them, but I like to keep that kind of thing to a minimum.
Perhaps I would be happier if the class was named differently and the selector applied more than just one style. But that’s not what you are doing, because one (or more) of those styles may appear elsewhere on the sheet.

Maybe it just needs a sensible balance in organising a maintainable style sheet.
How much repetition do you allow to avoid fragmentation and html almost hard coded to a particular style?

I think one question to ask is, what is the purpose of the CSS, to be small, or to be maintainable?
Nobody want’s bloat, but taking it to extremes, if you have a class for every value of every style property used in the name of speed, you may as well remove the file request for the external CSS and in-line everything.

Looking ahead, CSS variables may change the way we think and organise our CSS. They are already here, but may need to wait for the demise of IE.


#10

Because I keep things as minimal as I can (the “artfulness” of my design skills is woeful but development and maintenance are easier) I haven’t tried a CSS linter for a long time. I would imagine they have improved some since then?


#11

Same here, when I tried out CSS Lint a while back I was not impressed. Most of what it came up with was either out-dated, very opinionated or just plain nonsense.
I wonder if Stylelint is any better.


#12

Interesting points, much food for thought.

A lot depends on the size and complexity of the stylesheets and each case should be treated separately. Perhaps the OP could post an actual CSS example which would make it a lot easier to make specific suggestions.

I picked a bad example of choosing .bgs {background-color: snow;}. To solve the background colour change I would have introduced a new style so as not to confuse the issue and done a global replace “bgs” with “bgg”.

The majority of colours come in swatches and a better example would have been:

.sz0 {background-color: #fff; color: #333;}
.sz1 {background-color: #0ff; color: #00f;}
.sz2 {background-color: #ff0; color: #0f0;}
.sz3 {background-color: #0f0; color: #ff0;}
.sz4 {background-color: #9f9; color: #fff;} /* warnings */
.sz5 {background-color: #f00; color: #ff0;} /* problems */

Here are some typical classes most used to enhance the default DIV defaults:

.clb {clear: both} .cll {clear: left;} .clr {clear: right;}
.dib {display: inline-block}

.fll {float: left}.flr {float: right}
.fli {display: inline-flex}
.flx {display: flex}
.ftr {position: fixed; bottom: 0; left: 0; width: 100%;}

.hhh {display: none}
.lh2 {line-height: 2} 

.mga {margin: auto} 
.mg1 {margin-top: -1.2em;} 
.mg2 {margin-top: -2em;} 
.mg8 {margin-top: 12em;}

.ooo {border: 0; margin: 0; padding: 0}

.p42 {padding: 0.42em}
.pof {position: fixed; top: 0; right: 0; width: 100%; height: 4em; background-color: #ff0;}
.pob {position: fixed; bottom: 0; left: 0; width: 100%;}
.poa {position: absolute} .por {position: relative}

.tac {text-align: center}.tal {text-align: left}.tar {text-align: right}

.w11 {width: 11%;} .w22 {width: 22%;} .w33 {width: 33%;} 
.w42 {width: 42%;} .w55 {width: 55%;} .w88 {width: 88%; max-width: 50em;} 
.w99 {width: 100%;}

.z02 {z-index: 2}

Surprised no one has mentioned the CSS Clean utilities or even the Google Chrome Audi Feature:

https://www.labnol.org/internet/remove-unused-css/28635/


#13

Maybe it’s only because of how I’m used to doing things, and I guess a lot depends, but naming the classes for the styles seems problematic to me. That is, for example, if I wanted to change blockquote font family from serif to sans-serif, instead of changing

blockquote {font-family: serif;}

to

blockquote {font-family: sans-serif;} 

if I had

bqs {font-family: serif;} 
bqss {font-family: sans-serif;} 

I would need to change the class value for every blockquote.


#14

I just tried the following blockquote example using colours instead of font-styles and it worked OK:

Test

<?php 

$tmp = <<< ____TMP
  <blockquote class="fgr" cite="https://www.huxley.net/bnw/four.html">
      <p>Words can be like X-rays, if you use them properly – they'll go through anything. You read and you're pierced.</p>
  </blockquote>
  <cite>– Aldous Huxley, Brave New World</cite>
  <hr>
  <blockquote class="fgg" cite="https://www.huxley.net/bnw/four.html">
      <p>Words can be like X-rays, if you use them properly – they'll go through anything. You read and you're pierced.</p>
  </blockquote>
  <cite>– Aldous Huxley, Brave New World</cite>
____TMP;
echo $tmp;

The stylesheet:

.fgg {color: #0f0;} 
.fgr {color: red;}

Output:


#15

The style @John_Betong is using is known as atomic CSS or utility-first CSS. You can find a nice article on it here: https://frontstuff.io/in-defense-of-utility-first-css

Although it certainly has merit I would suggest that when you use it you give classes more descriptive names so when you come back to it on a few years time you can still see what they’re about instead of having to relearn the entire stylesheet.


#16

As for the original question of this thread I would suggest watching this video: https://m.youtube.com/watch?v=fvTryZjGyg8