Skip to content

CSS Minify & Beautify — C# source

Minify CSS (strip comments and whitespace, shorten hexes and decimals) or beautify it back to readable one-declaration-per-line form. Strings stay intact. Runs locally with a shareable link.

This is the C# implementation — the same logic the interactive tool runs, in a shareable, citable form.

// css-minify — CSS minifier & beautifier. C# port (canonical TS:
// src/lib/css-minify.ts; Go twin: cli/css-minify). One scanner masks string
// literals as "\x00n\x00" sentinels and drops /* */ comments; every textual
// rule then runs on the masked text — .NET regexes carry the TS
// backreferences natively, so each rule is a straight transcription of the
// TS pattern. minify — collapse whitespace, strip spaces around {} ; : , >
// (sibling + and ~ combinators keep theirs), drop the last semicolon before
// }, lowercase hexes, shorten #aabbcc → #abc (never 8-digit alpha), strip
// leading zeros (0.5 → .5) and trailing fraction zeros (1.50 → 1.5,
// 1.00 → 1, .00 → 0). beautify — one selector per block, one declaration
// per line at 2-space depth, each declaration keeping its own semicolon.
// Errors travel in result.Error (null = success); empty input is a
// successful empty output, never an error.
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;

namespace CosmoDev.CssMinify;

/// <summary>Mirrors the TS CssFormatResult union; Error is null on success.</summary>
public sealed record CssFormatResult(string Output, string? Error)
{
    public static CssFormatResult Ok(string output) => new(output, null);
    public static CssFormatResult Fail(string error) => new("", error);
}

public static class CssMinify
{
    private static readonly Regex Ws = new(@"\s+", RegexOptions.Compiled);
    private static readonly Regex StructStrip = new(@"\s*([{};:,>])\s*", RegexOptions.Compiled);
    private static readonly Regex TrailingSemis = new(@";+}", RegexOptions.Compiled);
    private static readonly Regex HexLower = new(@"#[0-9a-fA-F]{3,8}", RegexOptions.Compiled);
    private static readonly Regex HexPair = new(@"#([0-9a-f])\1([0-9a-f])\2([0-9a-f])\3([^0-9a-f]|$)", RegexOptions.Compiled);
    private static readonly Regex LeadingZero = new(@"(^|[^A-Za-z0-9_.#$%-])0+(\.[0-9]+)", RegexOptions.Compiled);
    private static readonly Regex FractionZeros = new(@"(\.[0-9]*[1-9])0+([^0-9]|$)", RegexOptions.Compiled);
    private static readonly Regex IntegralZeros = new(@"(^|[^A-Za-z0-9_.#$%-])([0-9]+)\.0+([^0-9]|$)", RegexOptions.Compiled);
    private static readonly Regex DotZeros = new(@"(^|[^A-Za-z0-9_.#$%-])\.0+([^0-9]|$)", RegexOptions.Compiled);
    private static readonly Regex Sentinel = new("\x00([0-9]+)\x00", RegexOptions.Compiled);

    /// <summary>Scan CSS into masked text where every string literal is
    /// replaced by a \x00n\x00 sentinel (n = index into strings) and every
    /// /* */ comment is dropped. A backslash escapes the next character.</summary>
    private static MaskResult Mask(string raw)
    {
        var outText = new StringBuilder();
        var strings = new List<string>();
        for (int i = 0; i < raw.Length; )
        {
            char ch = raw[i];
            if (ch == '"' || ch == '\'')
            {
                int start = i++;
                while (i < raw.Length && raw[i] != ch)
                {
                    if (raw[i] == '\\' && i + 1 < raw.Length) i++; // escaped char
                    i++;
                }
                if (i >= raw.Length) return MaskResult.Fail("Unterminated string");
                i++;
                strings.Add(raw.Substring(start, i - start));
                outText.Append('\x00').Append(strings.Count - 1).Append('\x00');
            }
            else if (ch == '/' && i + 1 < raw.Length && raw[i + 1] == '*')
            {
                int end = raw.IndexOf("*/", i + 2, StringComparison.Ordinal);
                if (end < 0) return MaskResult.Fail("Unterminated comment");
                i = end + 2;
            }
            else
            {
                outText.Append(ch);
                i++;
            }
        }
        return MaskResult.Ok(outText.ToString(), strings);
    }

    /// <summary>Substitute the sentinels back with the original literals.</summary>
    private static string Unmask(string text, List<string> strings) =>
        Sentinel.Replace(text, m =>
        {
            int n = int.Parse(m.Groups[1].Value);
            return n >= 0 && n < strings.Count ? strings[n] : m.Value;
        });

    /// <summary>Conservative minification — see the header for the rule list.</summary>
    public static CssFormatResult MinifyCss(string raw)
    {
        string text = raw.Trim();
        if (text.Length == 0) return CssFormatResult.Ok(""); // empty input is NOT an error
        MaskResult m = Mask(text);
        if (!m.Ok) return CssFormatResult.Fail(m.Error);
        string css = Ws.Replace(m.Value, " ");
        css = StructStrip.Replace(css, "$1");
        css = TrailingSemis.Replace(css, "}");
        css = css.Trim();
        css = HexLower.Replace(css, h => h.Value.ToLowerInvariant());
        css = HexPair.Replace(css, "#$1$2$3$4");
        css = LeadingZero.Replace(css, "$1$2");
        css = FractionZeros.Replace(css, "$1$2");
        css = IntegralZeros.Replace(css, "$1$2$3");
        // "${1}0$2": a bare $10 would be read as group 10, mirroring the TS.
        css = DotZeros.Replace(css, "${1}0$2");
        return CssFormatResult.Ok(Unmask(css, m.Strings));
    }

    /// <summary>Structural beautifier — 2-space indentation, declarations
    /// one per line; empty declarations (;;, dangling ;) are skipped.</summary>
    public static CssFormatResult BeautifyCss(string raw)
    {
        string text = raw.Trim();
        if (text.Length == 0) return CssFormatResult.Ok("");
        MaskResult m = Mask(text);
        if (!m.Ok) return CssFormatResult.Fail(m.Error);
        string css = Ws.Replace(m.Value, " ");
        var outText = new StringBuilder();
        var buf = new StringBuilder();
        int depth = 0;
        void Flush(bool semi)
        {
            string decl = buf.ToString().Trim();
            if (decl.Length != 0)
            {
                outText.Append(' ', 2 * depth).Append(decl);
                if (semi) outText.Append(';');
                outText.Append('\n');
            }
            buf.Clear();
        }
        foreach (char ch in css)
        {
            switch (ch)
            {
                case '{':
                    string sel = buf.ToString().Trim();
                    buf.Clear();
                    if (sel.Length == 0) return CssFormatResult.Fail("Block without a selector");
                    outText.Append(' ', 2 * depth).Append(sel).Append(" {\n");
                    depth++;
                    break;
                case '}':
                    Flush(false);
                    depth--;
                    if (depth < 0) return CssFormatResult.Fail("Unbalanced }");
                    outText.Append(' ', 2 * depth).Append("}\n");
                    break;
                case ';':
                    Flush(true);
                    break;
                default:
                    buf.Append(ch);
                    break;
            }
        }
        if (depth != 0) return CssFormatResult.Fail("Unclosed block");
        Flush(false);
        return CssFormatResult.Ok(Unmask(outText.ToString(), m.Strings));
    }
}

/// <summary>Carrier so Mask returns either the masked text (plus its string
/// table) or one of the pinned TS error strings.</summary>
internal sealed class MaskResult
{
    public string Value = "";
    public List<string> Strings = new();
    public string Error;

    public bool Ok => Error == null;

    public static MaskResult Ok(string value, List<string> strings) =>
        new() { Value = value, Strings = strings };
    public static MaskResult Fail(string error) => new() { Error = error };
}

Also available in 13 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →