rcssmin: CSS Minifier
RCSSmin is a CSS minifier written in Python, based on the semantics of the YUI compressor. It prioritizes speed over maximum compression, performing syntactical compression only by removing spaces, comments, and semicolons, while supporting various CSS hacks. It includes a C re-implementation (`rcssmin.c`) that significantly improves runtime performance. The current version is 1.2.2.
Warnings
- gotcha Installing `rcssmin` on Windows (and some other platforms) might require a C compiler (e.g., Visual C++ Build Tools) to build its faster C extension (`rcssmin.c`). Without a compiler, the installation might fall back to the slower pure Python implementation, or fail entirely if not properly handled by `pip`.
- gotcha `rcssmin` performs only *syntactical* CSS compression (e.g., stripping spaces, comments, semicolons). It does not perform *semantic* compression, such as removing empty CSS blocks, collapsing redundant properties, or short-handing properties. Users expecting deeper optimization should consider other tools or combine `rcssmin` with a semantic optimizer.
- gotcha By default, `rcssmin.cssmin` removes all comments. To preserve 'bang comments' (comments starting with an exclamation mark, e.g., `/*! License */`), you must explicitly set the `keep_bang_comments=True` parameter.
- gotcha While older versions of `rcssmin` and its documentation might mention Python 2.7 support, the library is primarily developed and tested for Python 3.6+. Recent distribution packages have also dropped Python 2 support. For reliable and performant operation, use Python 3.6 or newer.
Install
-
pip install rcssmin
Imports
- cssmin
from rcssmin import cssmin
Quickstart
import rcssmin
css_input = """\
/* This is a comment */
body {
color: #fff; /* inline comment */
font-size: 16px; /*! Important comment */
}
.container { margin: 0 auto; }
"""
# Basic minification
minified_css = rcssmin.cssmin(css_input)
print(f"Basic Minified:\n{minified_css}")
# Expected: body{color:#fff;font-size:16px}.container{margin:0 auto}
# Keep 'bang comments' (comments starting with !)
minified_with_bang = rcssmin.cssmin(css_input, keep_bang_comments=True)
print(f"\nMinified with Bang Comments:\n{minified_with_bang}")
# Expected: body{color:#fff;font-size:16px/*! Important comment */}.container{margin:0 auto}