Skip to content

Refactoring Techniques

Cristian Ontivero edited this page Oct 19, 2017 · 1 revision

Restructuring Techniques

Removing empty style blocks

Empty rules such as the following, are removed:

* { }
div { ; }
a {
  /*color: blue; */
}
@media print {
  .nothing { }
}

Removing duplicate selectors in a rule

.off-canvas-content,
.off-canvas-content
{ /* some declarations here */ }
becomes:
.off-canvas-content
{ /* some declarations here */ }

Removing overwritten declarations

Overwritten declarations can be removed, as in the example below:

#case1 {
  margin-top: 1px;
  margin-top: 2px;
}
#case2 {
  margin-right: 1px !important;
  margin-right: 2px;
}
#case3 {
  margin-bottom: 1px;
  margin-bottom: 2px !important;
}
#case4 {
  margin-left: 1px !important;
  margin-left: 2px !important;
}
becomes:
#case1 {
  margin-top: 2px;
}
#case2 {
  margin-right: 1px !important;
}
#case3 {
  margin-bottom: 2px !important;
}
#case4 {
 margin-left: 2px !important;
}

Merging Longhands into Their Shorthands

For example, this:

#mergeExample {
  margin: 0;
  margin-top: 5px;
  padding: 2px;
  padding-left: 0;
  padding-right: 0;
}
becomes
#mergeExample {
  margin: 5px 0 0 0; /* this later becomes 5px 0 0 */
  padding: 2px 0 2px 0; /* this also becomes 2px 0 */
}

Collapsing Longhands into their Shorthand

When all the longhands of a shorthand are present in a rule, they may be replaced for their shorthand. For example:

.aRule {
  padding-top: 1q;
  padding-bottom: 3q;
  padding-left: 4q;
  padding-right: 2q;
}
can be rewritten as:
.aRule {
  padding: 1q 2q 3q 4q;
}
Note that for this to be safe, every longhand must be present, because values missing from a shorthand get reset to their initial values. Thus, Hasmin only collapses longhands when it is safe to do so.

Merging adjacent @media rules

Adjacent @media rules with identical conditions, such as:

@media all and (min-width: 24rem) {
  .a { font-size: 1.2rem; }
}
@media all and (min-width: 24rem) {
  .b { padding-left: .25rem; padding-right: .25rem; }
}
get merged into one:
@media all and (min-width: 24rem) {
  .a { font-size: 1.2rem; }
  .b { padding-left: .25rem; padding-right: .25rem; }
}