CSS Shorthand Optimization — Collapse Verbose Declarations

Learn how CSS shorthand optimization reduces stylesheet size by collapsing verbose declarations into shorthand properties. Covers margin, padding, background, font, and border shorthands.

CSS

Detailed Explanation

CSS Shorthand Optimization

CSS shorthand properties allow multiple related values to be set with a single declaration. Minifiers detect verbose longhand declarations and collapse them into their shorthand equivalents, reducing both file size and redundancy.

Common Shorthand Collapses

Margin and Padding:

/* Longhand */
.box {
  margin-top: 10px;
  margin-right: 20px;
  margin-bottom: 10px;
  margin-left: 20px;
}

/* Shorthand */
.box {
  margin: 10px 20px;
}

The shorthand margin value follows the pattern: top right bottom left. When top equals bottom and right equals left, it collapses to two values. When all four are equal, it collapses to one.

Background:

/* Longhand */
.hero {
  background-color: #f0f0f0;
  background-image: url(bg.png);
  background-repeat: no-repeat;
  background-position: center center;
  background-size: cover;
}

/* Shorthand */
.hero {
  background: #f0f0f0 url(bg.png) no-repeat center / cover;
}

Font:

/* Longhand */
.text {
  font-style: italic;
  font-weight: 700;
  font-size: 16px;
  line-height: 1.5;
  font-family: Arial, sans-serif;
}

/* Shorthand */
.text {
  font: italic 700 16px/1.5 Arial, sans-serif;
}

When Shorthand Optimization Is Unsafe

Shorthand properties reset omitted sub-properties to their initial values. This can cause unintended side effects:

/* Original intent: only change background-color */
.card {
  background-image: url(pattern.svg);
  background-color: white;
}

/* Unsafe shorthand collapses to: */
.card {
  background: white;
  /* background-image is now reset to 'none'! */
}

Smart minifiers like cssnano detect this and only apply shorthand when all sub-properties are explicitly set in the same rule block.

Size Impact

Shorthand optimization typically saves 5-15% of CSS file size on top of basic whitespace removal. The savings are most significant in stylesheets with verbose, hand-written CSS that uses longhand properties consistently.

Use Case

CSS shorthand optimization is particularly valuable for legacy codebases where developers used longhand properties for clarity. Applying shorthand collapsing during the build step keeps source code readable while shipping optimized CSS to users.

Try It — Code Minifier

Open full tool