0
# CSS Serialization
1
2
Convert CSS objects back to formatted CSS text with extensive customization options for output formatting, indentation, and style preferences.
3
4
## Capabilities
5
6
### CSSSerializer Class
7
8
Main serialization class with configurable formatting preferences.
9
10
```python { .api }
11
class CSSSerializer:
12
"""
13
CSS serialization with comprehensive formatting control.
14
15
Constructor:
16
CSSSerializer(prefs=None)
17
18
Parameters:
19
- prefs (Preferences): Formatting preferences object (uses defaults if None)
20
"""
21
22
# Properties
23
prefs: 'Preferences' # Formatting preferences
24
25
# Main Serialization Methods
26
def do_CSSStyleSheet(stylesheet):
27
"""
28
Serialize complete CSS stylesheet.
29
30
Parameters:
31
- stylesheet (CSSStyleSheet): Stylesheet to serialize
32
33
Returns:
34
str: Formatted CSS text
35
"""
36
37
def do_CSSStyleRule(rule):
38
"""
39
Serialize CSS style rule.
40
41
Parameters:
42
- rule (CSSStyleRule): Style rule to serialize
43
44
Returns:
45
str: Formatted CSS rule text
46
"""
47
48
def do_CSSMediaRule(rule):
49
"""
50
Serialize @media rule with nested rules.
51
52
Parameters:
53
- rule (CSSMediaRule): Media rule to serialize
54
55
Returns:
56
str: Formatted @media rule text
57
"""
58
59
def do_CSSImportRule(rule):
60
"""
61
Serialize @import rule.
62
63
Parameters:
64
- rule (CSSImportRule): Import rule to serialize
65
66
Returns:
67
str: Formatted @import rule text
68
"""
69
70
def do_CSSPageRule(rule):
71
"""
72
Serialize @page rule.
73
74
Parameters:
75
- rule (CSSPageRule): Page rule to serialize
76
77
Returns:
78
str: Formatted @page rule text
79
"""
80
81
def do_CSSFontFaceRule(rule):
82
"""
83
Serialize @font-face rule.
84
85
Parameters:
86
- rule (CSSFontFaceRule): Font-face rule to serialize
87
88
Returns:
89
str: Formatted @font-face rule text
90
"""
91
92
def do_CSSNamespaceRule(rule):
93
"""
94
Serialize @namespace rule.
95
96
Parameters:
97
- rule (CSSNamespaceRule): Namespace rule to serialize
98
99
Returns:
100
str: Formatted @namespace rule text
101
"""
102
103
def do_CSSCharsetRule(rule):
104
"""
105
Serialize @charset rule.
106
107
Parameters:
108
- rule (CSSCharsetRule): Charset rule to serialize
109
110
Returns:
111
str: Formatted @charset rule text
112
"""
113
114
def do_css_CSSStyleDeclaration(style, separator=None, omit=True):
115
"""
116
Serialize CSS style declarations.
117
118
Parameters:
119
- style (CSSStyleDeclaration): Style declarations to serialize
120
- separator (str): Property separator (default: uses preferences)
121
- omit (bool): Whether to omit last semicolon
122
123
Returns:
124
str: Formatted declarations text
125
"""
126
127
def do_CSSComment(comment):
128
"""
129
Serialize CSS comment.
130
131
Parameters:
132
- comment (CSSComment): Comment to serialize
133
134
Returns:
135
str: Formatted comment text
136
"""
137
```
138
139
### Preferences Class
140
141
Serialization formatting preferences controlling output appearance.
142
143
```python { .api }
144
class Preferences:
145
"""
146
Serialization formatting preferences for controlling CSS output appearance.
147
"""
148
149
# Basic Formatting
150
indent: str # Indentation string (default: ' ' - 4 spaces)
151
lineSeparator: str # Line ending character (default: '\\n')
152
omitLastSemicolon: bool # Omit semicolon after last property (default: True)
153
154
# Rule Formatting
155
keepEmptyRules: bool # Include empty rules in output (default: False)
156
keepComments: bool # Include CSS comments in output (default: True)
157
keepAllProperties: bool # Preserve all properties including duplicates (default: False)
158
159
# Property Formatting
160
defaultPropertyName: bool # Use normalized property names (default: True)
161
defaultAtKeyword: bool # Use default @keyword form (default: True)
162
163
# Value Formatting
164
minimizeColorHash: bool # Minimize color hashes #FFFFFF → #FFF (default: True)
165
166
# Advanced Options
167
lineNumbers: bool # Add line numbers to output (default: False)
168
validOnly: bool # Only output valid CSS (default: False)
169
170
# Methods
171
def __init__(**kwargs):
172
"""
173
Initialize preferences with custom values.
174
175
Parameters:
176
- **kwargs: Any preference property and its value
177
"""
178
179
def copy():
180
"""
181
Create copy of preferences.
182
183
Returns:
184
Preferences: Copy of current preferences
185
"""
186
```
187
188
### Global Serializer Functions
189
190
Global functions for setting and getting the default serializer.
191
192
```python { .api }
193
def setSerializer(serializer):
194
"""
195
Set the global serializer used by all cssutils classes.
196
197
Parameters:
198
- serializer (CSSSerializer): Serializer instance to use globally
199
"""
200
201
def getSerializer():
202
"""
203
Get the current global serializer.
204
205
Returns:
206
CSSSerializer: Current global serializer instance
207
"""
208
```
209
210
## Usage Examples
211
212
### Basic Serialization
213
214
```python
215
import cssutils
216
from cssutils.serialize import CSSSerializer
217
218
# Parse CSS
219
css = """
220
body {
221
margin: 0;
222
padding: 0;
223
font-family: Arial, sans-serif;
224
}
225
226
h1 {
227
color: #333;
228
font-size: 24px;
229
}
230
"""
231
232
sheet = cssutils.parseString(css)
233
234
# Use default serialization
235
print("Default serialization:")
236
print(sheet.cssText)
237
238
# Use custom serializer
239
serializer = CSSSerializer()
240
print("\nCustom serialization:")
241
print(serializer.do_CSSStyleSheet(sheet))
242
```
243
244
### Custom Formatting Preferences
245
246
```python
247
import cssutils
248
from cssutils.serialize import CSSSerializer, Preferences
249
250
# Create custom preferences
251
prefs = Preferences(
252
indent=' ', # 2-space indent
253
lineSeparator='\n', # Unix line endings
254
omitLastSemicolon=False, # Keep all semicolons
255
keepEmptyRules=True, # Keep empty rules
256
minimizeColorHash=False, # Don't minimize colors
257
)
258
259
# Create serializer with preferences
260
serializer = CSSSerializer(prefs=prefs)
261
262
# Parse and serialize with custom formatting
263
css = """
264
body{margin:0;padding:0;color:#ffffff}
265
h1{color:red;}
266
.empty{}
267
"""
268
269
sheet = cssutils.parseString(css)
270
formatted = serializer.do_CSSStyleSheet(sheet)
271
print(formatted)
272
```
273
274
### Compact vs Expanded Output
275
276
```python
277
import cssutils
278
from cssutils.serialize import CSSSerializer, Preferences
279
280
css = """
281
.navigation {
282
background-color: #333333;
283
border: 1px solid #666666;
284
margin: 0;
285
padding: 10px 20px;
286
}
287
"""
288
289
sheet = cssutils.parseString(css)
290
291
# Expanded format (default)
292
expanded_prefs = Preferences(
293
indent=' ',
294
omitLastSemicolon=True,
295
minimizeColorHash=False
296
)
297
expanded_serializer = CSSSerializer(prefs=expanded_prefs)
298
299
print("Expanded format:")
300
print(expanded_serializer.do_CSSStyleSheet(sheet))
301
302
# Compact format
303
compact_prefs = Preferences(
304
indent='',
305
lineSeparator='',
306
omitLastSemicolon=True,
307
minimizeColorHash=True
308
)
309
compact_serializer = CSSSerializer(prefs=compact_prefs)
310
311
print("\nCompact format:")
312
print(compact_serializer.do_CSSStyleSheet(sheet))
313
```
314
315
### Serializing Individual Rules
316
317
```python
318
import cssutils
319
from cssutils.serialize import CSSSerializer
320
321
css = """
322
@import url("base.css") screen;
323
@media print {
324
body { font-size: 12pt; }
325
}
326
h1 { color: blue; }
327
"""
328
329
sheet = cssutils.parseString(css)
330
serializer = CSSSerializer()
331
332
# Serialize individual rules
333
for i, rule in enumerate(sheet.cssRules):
334
print(f"Rule {i} ({rule.type}):")
335
336
if rule.type == rule.IMPORT_RULE:
337
print(serializer.do_CSSImportRule(rule))
338
elif rule.type == rule.MEDIA_RULE:
339
print(serializer.do_CSSMediaRule(rule))
340
elif rule.type == rule.STYLE_RULE:
341
print(serializer.do_CSSStyleRule(rule))
342
343
print()
344
```
345
346
### Style Declaration Serialization
347
348
```python
349
import cssutils
350
from cssutils.serialize import CSSSerializer
351
352
# Create style declaration
353
style = cssutils.css.CSSStyleDeclaration()
354
style.setProperty('color', 'red')
355
style.setProperty('margin', '10px 20px')
356
style.setProperty('font-weight', 'bold', 'important')
357
358
serializer = CSSSerializer()
359
360
# Different serialization options
361
print("Normal:")
362
print(serializer.do_css_CSSStyleDeclaration(style))
363
364
print("\nWith custom separator:")
365
print(serializer.do_css_CSSStyleDeclaration(style, separator='; '))
366
367
print("\nWithout omitting last semicolon:")
368
print(serializer.do_css_CSSStyleDeclaration(style, omit=False))
369
```
370
371
### Global Serializer Configuration
372
373
```python
374
import cssutils
375
from cssutils.serialize import CSSSerializer, Preferences
376
377
# Create custom global serializer
378
custom_prefs = Preferences(
379
indent=' ',
380
minimizeColorHash=True,
381
keepComments=False
382
)
383
custom_serializer = CSSSerializer(prefs=custom_prefs)
384
385
# Set as global serializer
386
cssutils.setSerializer(custom_serializer)
387
388
# All cssutils objects now use custom serializer
389
css = """
390
/* This comment will be removed */
391
body {
392
color: #ffffff; /* This becomes #fff */
393
margin: 0;
394
}
395
"""
396
397
sheet = cssutils.parseString(css)
398
print("With custom global serializer:")
399
print(sheet.cssText)
400
401
# Reset to default
402
cssutils.setSerializer(cssutils.CSSSerializer())
403
```
404
405
### Handling Different CSS Constructs
406
407
```python
408
import cssutils
409
from cssutils.serialize import CSSSerializer
410
411
# CSS with various constructs
412
css = """
413
@charset "utf-8";
414
@namespace svg "http://www.w3.org/2000/svg";
415
@import "base.css";
416
417
@media screen and (max-width: 768px) {
418
body { font-size: 14px; }
419
}
420
421
@page :first {
422
margin-top: 2in;
423
}
424
425
@font-face {
426
font-family: 'Custom';
427
src: url('custom.woff');
428
}
429
430
/* Main styles */
431
body {
432
margin: 0;
433
color: #333;
434
}
435
436
svg|rect {
437
fill: blue;
438
}
439
"""
440
441
sheet = cssutils.parseString(css)
442
serializer = CSSSerializer()
443
444
print("Complete stylesheet serialization:")
445
print(serializer.do_CSSStyleSheet(sheet))
446
```
447
448
### Line Numbers and Debugging
449
450
```python
451
import cssutils
452
from cssutils.serialize import CSSSerializer, Preferences
453
454
# Enable line numbers for debugging
455
debug_prefs = Preferences(
456
lineNumbers=True,
457
keepComments=True
458
)
459
debug_serializer = CSSSerializer(prefs=debug_prefs)
460
461
css = """
462
body {
463
margin: 0;
464
padding: 0;
465
}
466
467
h1 {
468
color: blue;
469
}
470
"""
471
472
sheet = cssutils.parseString(css)
473
print("With line numbers:")
474
print(debug_serializer.do_CSSStyleSheet(sheet))
475
```
476
477
### Preserving All Properties
478
479
```python
480
import cssutils
481
from cssutils.serialize import CSSSerializer, Preferences
482
483
# CSS with duplicate properties (for browser compatibility)
484
css = """
485
.box {
486
background: red; /* Fallback */
487
background: linear-gradient(to bottom, red, blue);
488
border-radius: 5px; /* Standard */
489
-webkit-border-radius: 5px; /* Webkit prefix */
490
-moz-border-radius: 5px; /* Mozilla prefix */
491
}
492
"""
493
494
sheet = cssutils.parseString(css)
495
496
# Default behavior (removes duplicates)
497
default_serializer = CSSSerializer()
498
print("Default (removes duplicates):")
499
print(default_serializer.do_CSSStyleSheet(sheet))
500
501
# Keep all properties
502
preserve_prefs = Preferences(keepAllProperties=True)
503
preserve_serializer = CSSSerializer(prefs=preserve_prefs)
504
print("\nKeeping all properties:")
505
print(preserve_serializer.do_CSSStyleSheet(sheet))
506
```