0
# CSS Compressor
1
2
A Python port of YUI CSS Compressor that provides comprehensive CSS minification and compression capabilities. CSS Compressor removes unnecessary whitespace, comments, and redundant code while optimizing colors, properties, and syntax to produce smaller CSS files with identical functionality.
3
4
## Package Information
5
6
- **Package Name**: csscompressor
7
- **Language**: Python
8
- **Installation**: `pip install csscompressor`
9
- **Version**: 0.9.4
10
- **License**: BSD
11
12
## Core Imports
13
14
```python
15
from csscompressor import compress, compress_partitioned
16
```
17
18
Module import:
19
20
```python
21
import csscompressor
22
# Use: csscompressor.compress()
23
```
24
25
## Basic Usage
26
27
```python
28
from csscompressor import compress
29
30
# Basic CSS compression
31
css_input = '''
32
body {
33
background-color: #ffffff;
34
color: rgba(0, 0, 0, 1);
35
margin: 0px 0px 0px 0px;
36
}
37
.header {
38
font-size: 1.0em;
39
padding: 10px;
40
}
41
'''
42
43
compressed = compress(css_input)
44
print(compressed)
45
# Output: body{background-color:#fff;color:#000;margin:0}.header{font-size:1em;padding:10px}
46
47
# Compress with line length limit for source control
48
compressed_wrapped = compress(css_input, max_linelen=80)
49
50
# Preserve important comments
51
css_with_comments = '''
52
/*! Important copyright notice */
53
/* Regular comment that will be removed */
54
body { color: red; }
55
'''
56
compressed_with_preserved = compress(css_with_comments, preserve_exclamation_comments=True)
57
```
58
59
## Command Line Usage
60
61
CSS Compressor can be used directly from the command line:
62
63
```bash
64
# Compress a single file to stdout
65
python -m csscompressor styles.css
66
67
# Compress multiple files (concatenated with double newlines) with line breaks
68
python -m csscompressor file1.css file2.css --line-break 80
69
70
# Output to a specific file
71
python -m csscompressor input.css -o compressed.css
72
73
# Get help
74
python -m csscompressor --help
75
```
76
77
Command line arguments:
78
- `input`: One or more CSS files to compress (files are concatenated with `\n\n` before compression)
79
- `--line-break <column>`: Insert line break after specified column number
80
- `-o, --output <file>`: Write output to file instead of stdout
81
82
Note: The command line interface always uses `preserve_exclamation_comments=True` and processes multiple input files by concatenating them with double newlines before compression.
83
84
## Capabilities
85
86
### CSS Compression
87
88
Compresses CSS stylesheets into a single optimized string with extensive minification features.
89
90
```python { .api }
91
def compress(css, max_linelen=0, preserve_exclamation_comments=True):
92
"""Compress given CSS stylesheet.
93
94
Parameters:
95
96
- css : str
97
An str with CSS rules.
98
99
- max_linelen : int = 0
100
Some source control tools don't like it when files containing lines longer
101
than, say 8000 characters, are checked in. This option is used in
102
that case to split long lines after a specific column.
103
104
- preserve_exclamation_comments : boolean = True
105
Some stylesheets contain /*! ... */ comment block which used for copyright
106
notices or else. By default compress dont remove them like other comment
107
blocks. It will lead to bigger file size. but once you decide to remove
108
them just set this parameter to False.
109
110
Returns a ``str`` object with compressed CSS.
111
112
Raises:
113
ValueError: For malformed CSS (unbalanced braces, malformed url() or calc() expressions)
114
"""
115
```
116
117
### Partitioned CSS Compression
118
119
Compresses CSS into multiple strings to work around Internet Explorer's 4096 rule limit per stylesheet file.
120
121
```python { .api }
122
def compress_partitioned(css,
123
max_linelen=0,
124
max_rules_per_file=4000,
125
preserve_exclamation_comments=True):
126
"""Compress given CSS stylesheet into a set of files.
127
128
Parameters:
129
130
- css : str
131
CSS rules to compress
132
133
- max_linelen : int = 0
134
Has the same meaning as for "compress()" function.
135
136
- max_rules_per_file : int = 4000
137
Internet Explorers <= 9 have an artificial max number of rules per CSS
138
file (4096; http://blogs.msdn.com/b/ieinternals/archive/2011/05/14/10164546.aspx)
139
When ``max_rules_per_file`` is a positive number, the function *always* returns
140
a list of ``str`` objects, each limited to contain less than the passed number
141
of rules.
142
143
- preserve_exclamation_comments : boolean = True
144
Has the same meaning as for "compress()" function.
145
146
Always returns a ``list`` of ``str`` objects with compressed CSS.
147
148
Raises:
149
ValueError: For malformed CSS (unbalanced braces)
150
AssertionError: If max_rules_per_file is not positive
151
"""
152
```
153
154
## Compression Features
155
156
CSS Compressor performs numerous optimizations to reduce file size:
157
158
### Whitespace and Comments
159
- Removes unnecessary whitespace and line breaks
160
- Strips regular comments while preserving important ones (/*! ... */)
161
- Normalizes remaining whitespace to single spaces
162
163
### Color Optimization
164
- Converts `rgb(51,102,153)` to `#336699`
165
- Compresses hex colors from `#AABBCC` to `#ABC` when possible
166
- Converts color names (e.g., `#f00` to `red` for common colors)
167
- Handles color functions like `hsl()` and `hsla()`
168
169
### Property Optimization
170
- Removes default values and units where possible
171
- Converts `0px`, `0em`, `0%` to just `0`
172
- Shortens floating point numbers (`0.5` to `.5`, `-0.5` to `-.5`)
173
- Combines redundant properties (`margin: 0 0 0 0` to `margin: 0`)
174
- Optimizes `background-position` and `transform-origin` values
175
176
### CSS Function Handling
177
- Preserves `calc()` expressions with proper whitespace
178
- Handles `url()` data URIs and file paths correctly
179
- Supports CSS gradients and filters
180
- Manages browser-specific prefixes and hacks
181
182
### IE Compatibility
183
- Preserves IE-specific CSS hacks and filters
184
- Handles `progid:DXImageTransform.Microsoft` filters
185
- Maintains compatibility with IE6-9 quirks
186
- Supports `-o-device-pixel-ratio` for Opera
187
188
### Error Handling
189
190
The compressor validates CSS syntax and raises errors for malformed input:
191
192
**ValueError Conditions:**
193
- Unbalanced curly braces in CSS rules
194
- Malformed `url()` expressions without proper closing
195
- Malformed `calc()` expressions without proper structure
196
- Invalid CSS syntax that prevents proper parsing
197
198
**AssertionError Conditions:**
199
- `max_rules_per_file` parameter is not positive (≤ 0) in `compress_partitioned()`
200
201
**Common error scenarios:**
202
```python
203
# Unbalanced braces - missing closing brace
204
compress("body { color: red") # Raises ValueError: malformed css
205
206
# Malformed url() without closing parenthesis
207
compress("body { background: url('image.png' }") # Raises ValueError: malformed css
208
209
# Invalid calc() expression structure
210
compress("div { width: calc(10px- }") # Raises ValueError: malformed css
211
212
# Invalid max_rules_per_file parameter
213
compress_partitioned("body{}", max_rules_per_file=0) # Raises AssertionError
214
215
# Unbalanced braces in partitioned compression
216
compress_partitioned("body { color: red") # Raises ValueError: malformed CSS: non-balanced curly-braces
217
```
218
219
**Error Sources:**
220
- Line 149 in `_preserve_call_tokens()`: Malformed url() or calc() expressions
221
- Line 529 in `compress_partitioned()`: Invalid max_rules_per_file parameter assertion
222
- Lines 549, 555 in `compress_partitioned()`: Unbalanced curly braces during partitioning
223
224
## Advanced Usage Examples
225
226
### Source Control Integration
227
```python
228
# Long lines can cause issues with some source control tools
229
css = "body { /* very long CSS rule */ }"
230
compressed = compress(css, max_linelen=120)
231
```
232
233
### Build System Integration
234
```python
235
# Process multiple CSS files for production
236
css_files = ['base.css', 'components.css', 'theme.css']
237
all_css = []
238
239
for file_path in css_files:
240
with open(file_path, 'r') as f:
241
all_css.append(f.read())
242
243
# Combine and compress all CSS
244
combined_css = '\n\n'.join(all_css)
245
compressed = compress(combined_css, preserve_exclamation_comments=True)
246
247
# Write to production file
248
with open('dist/styles.min.css', 'w') as f:
249
f.write(compressed)
250
```
251
252
### IE Compatibility Mode
253
```python
254
# Split CSS for IE compatibility (4096 rule limit)
255
large_css = open('large-stylesheet.css').read()
256
css_parts = compress_partitioned(large_css, max_rules_per_file=4000)
257
258
# Write multiple files for IE
259
for i, css_part in enumerate(css_parts):
260
with open(f'styles-{i+1}.min.css', 'w') as f:
261
f.write(css_part)
262
```
263
264
## Version Information
265
266
The package version can be accessed programmatically:
267
268
```python { .api }
269
import csscompressor
270
print(csscompressor.__version__) # Returns '0.9.4'
271
```
272
273
Note: The `__version__` constant in the source code shows '0.9.4' while setup.py may show different version numbers due to development versioning practices. The source code `__version__` is the authoritative version identifier.