Skip to content

CSS minifier breaks calc() expressions with operators on separate lines #450

@colethorsen

Description

@colethorsen

Description

The CSS minifier removes newlines in a way that breaks calc() expressions when addition or subtraction operators are on separate lines from their operands. I use Prettier to enforce style on CSS and in this specific case this is how it formatted it.

Expected Behavior

calc() expressions should maintain required whitespace around + and - operators per the CSS spec, even when the source has line breaks.

Actual Behavior

When a calc() expression has an operator and operand on separate lines, the minifier removes the newline without preserving the required space, producing invalid CSS.

Example

Input CSS:

.link {
    padding-right: calc(
        30px +
            var(
                --nav-link-padding-right,
                var(--nav-link-padding-x, var(--nav-link-padding, 10px))
            )
    );
}

Current Output:

.link{padding-right:calc(30px+var(--nav-link-padding-right,var(--nav-link-padding-x,var(--nav-link-padding,10px))))}

Expected Output:

.link{padding-right:calc(30px + var(--nav-link-padding-right,var(--nav-link-padding-x,var(--nav-link-padding,10px))))}

CSS Specification

Per the CSS Values and Units Module Level 3, whitespace is required on both sides of + and - operators in calc() expressions (but not for * and /).

Workaround

Pre-process CSS by converting newlines to spaces before minification:

$css = str_replace(["\r\n", "\r", "\n"], ' ', $css);

$minifier = new Minify\CSS;
$minifier->add($css);
$minified = $minifier->minify();

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions