CSS Minifier — Developer Code Samples

CSS minification removes whitespace, comments, and redundant characters to reduce file size without changing visual output. Python's csscompressor, Node.js's csso or clean-css, and basic regex approaches all achieve significant size reductions.

Try the interactive version online: Open CSS Minifier Tool →

Parameters

Parameter Type Required Description
css str Yes CSS string or file contents to minify
remove_comments bool No Remove all CSS comments (default: True)
collapse_whitespace bool No Collapse multiple spaces/newlines (default: True)

Returns: Minified CSS string with reduced file size

Code Examples

import re

def minify_css(css):
    """
    Minify CSS by removing comments, whitespace, and redundant characters.
    Pure Python, no external dependencies.
    """
    # Remove comments (/* ... */)
    css = re.sub(r'/\*.*?\*/', '', css, flags=re.DOTALL)

    # Remove whitespace around common characters
    css = re.sub(r'\s*([{}:;,>~+])\s*', r'\1', css)

    # Collapse multiple whitespace into single space
    css = re.sub(r'\s+', ' ', css)

    # Remove semicolon before closing brace
    css = re.sub(r';\}', '}', css)

    # Remove leading/trailing whitespace
    css = css.strip()

    return css

# Example usage
sample_css = """
/* Main navigation styles */
.nav {
    display: flex;
    align-items: center;
    background-color: #ffffff;
    padding: 16px 24px;
}

.nav-link {
    color: #333333;
    text-decoration: none;
    font-size: 14px;
    margin: 0 8px;
}

.nav-link:hover {
    color: #0066cc;
}
"""

minified = minify_css(sample_css)
print(minified)
# Output: .nav{display:flex;align-items:center;background-color:#ffffff;padding:16px 24px}.nav-link{color:#333333;text-decoration:none;font-size:14px;margin:0 8px}.nav-link:hover{color:#0066cc}

original_size = len(sample_css.encode())
minified_size = len(minified.encode())
print(f"Original: {original_size} bytes | Minified: {minified_size} bytes | Saved: {100*(1 - minified_size/original_size):.1f}%")