CU3ED
CU3ED

Reputation: 478

How to merge multiple CSS rules from duplicated selectors?

Precursor:

Under normal circumstances, I would never do this.

I have a CSS file that I am currently collaborating on with another person. I built the file initially, then they have added rules to it after the fact. But, instead of adding rules to selectors that already exist, they have duplicated selectors everywhere. I don't even want to get into how disorganized the file has become. The problem is that the duplicated selectors are spread out all over the file now and it could take some time to sort it out.

Anyway, I am currently in the process of trying to clean up the file. I have tried beautify, css format, etc in my editor (ST3), which cleans up fine but still leaves the duplicate selectors. I have tried various online tools like CSS Lint, ProCSSor, Dirty Markup, CleanCSS and so far none of these tools give me the desired result.

Is there any way that these selectors can be merged by some other means instead of manually?

Here's an example of my situation, just for reference:

I'd like to turn this...

.sameClass {
  float: left;
  width: 100%;
  margin: 0;
  padding: 0;
}

.differentClass {
  border: none;
  background: black;
  padding: 0;
}

.sameClass {
  font-weight: bold;
  font-size: 24px;
  display: inline-block;
}

into this...

.sameClass {
  float: left;
  width: 100%;
  margin: 0;
  padding: 0;
  font-weight: bold;
  font-size: 24px;
  display: inline-block;
}

.differentClass {
  border: none;
  background: black;
  padding: 0;
}

Upvotes: 8

Views: 7741

Answers (2)

djibe
djibe

Reputation: 3038

CSSO (Github project) is the tool will help you merge identical CSS classes. It can be configured to execute some cleaning, compaction and restructuring.

Test in sandbox here : https://css.github.io/csso/csso.html

// Input
.card {box-shadow: none;}
.foo { color: #ff0000; }
.bar { color: rgba(255, 0, 0, 1); }
.card {border: 1px solid grey;}

// Output compacted + merged
.bar,.foo{color:red}
.card {box-shadow: none;border: 1px solid grey;}

Upvotes: 7

user663031
user663031

Reputation:

A simplistic approach would be to sort your CSS file(s) by selector. This can be done by considering each rule as a "paragraph" (meaning you will have to ensure there are empty lines between rules, and nowhere else), and then using your editor's "sort paragraph" feature, if it has one. For instance, emacs has the M-x sort-paragraphs command.

Once multiple rules for the same selector are grouped together, you can manually go in and combine them.

Upvotes: 0

Related Questions