Home > Back-end >  Removing redundant CSS
Removing redundant CSS

Time:06-20

I'm trying to optimize a site for speed and I'd like to remove redundant CSS.

NOTE: I am not trying to remove "unused CSS" (There are dozens of easy-to-find solutions for that task).

The issue I'm having is a CSS declaration like the following: (This is a very simplified example)

<style>
      #header { width: 800px; background-color: #333; }
      h2 {font-size: 24px; }
      h3 {font-size: 16px; }
      #header { background-color: #777; }
</style>

I'm looking for a way to intelligently combine the redundant #header declaration (so that the width:800px is preserved, but the only color is #777) -- except for a site with thousands of redundant CSS declarations.

Is there some elegant way to do this programmatically?

CodePudding user response:

Is there some elegant way to do this programmatically?

Not really. The order of rules matters and their precedence, so without the DOMs to which it is applied you can't say for sure which rules can be moved or combined. For some, it might be possible but for most of them, you need to see how they are applied.

If you take a look at this:

#test3 .test2 {
  border: 1px solid red;
  color: blue;
}

#test.test {
  border: 1px solid green;
  color: red;
}

#test3 .test2 {
  color: green;
}
<div id="test3">
  <div id="test" >
    test
  </div>
</div>

Combining those two #test3 .test2 in one rule is not possible, even so #test.test does not seem to be related to those (if only looking at the CSS code).

Removing unused styles is already complicated because you need all possible states of the DOM you have.

But combining them is even more complex. Not impossible but nothing that can be easily done and especially nothing that would fit into one answer.

You would do something like that:

  • For every state of the DOMs you want to support you would need to have the information to which elements each rule is applied, and the information on which rules are applied to each element and with which precedence.
  • For each element, you would sort those rules based on the precedence
  • For two rules you want to merge you would then check to which elements they are applied, and if they can be merged, based on the ordering of those rules and the properties that those change.
  • And if that is true for each element you can merge them.

CodePudding user response:

You can use CSS Variables to avoid redundand code.

Example

:root {
  --main-bg-color: brown;
}

.one {
    background-color: var(--main-bg-color);
}
  •  Tags:  
  • css
  • Related