0
# CSS Stylesheets
1
2
CSS stylesheet management implementing DOM Level 2 Style Sheets specification. Create, manipulate, and manage complete CSS stylesheets with rules, media queries, namespaces, and variables.
3
4
## Capabilities
5
6
### CSSStyleSheet Class
7
8
Main stylesheet container representing a complete CSS document with all rules and metadata.
9
10
```python { .api }
11
class CSSStyleSheet:
12
"""
13
CSS stylesheet implementing DOM Level 2 CSSStyleSheet interface.
14
15
Constructor:
16
CSSStyleSheet(href=None, media=None, title='', disabled=None,
17
ownerNode=None, parentStyleSheet=None, readonly=False,
18
ownerRule=None, validating=True)
19
20
Parameters:
21
- href (str): URL of the stylesheet
22
- media (str/MediaList): Media query list for stylesheet applicability
23
- title (str): Advisory title for the stylesheet
24
- disabled (bool): Whether stylesheet is disabled
25
- ownerNode: DOM node that owns this stylesheet
26
- parentStyleSheet: Parent stylesheet for imported sheets
27
- readonly (bool): Whether stylesheet can be modified
28
- ownerRule: CSS rule that imported this stylesheet
29
- validating (bool): Whether to validate modifications
30
"""
31
32
# Properties
33
cssRules: 'CSSRuleList' # All rules in the stylesheet
34
media: 'MediaList' # Media query list
35
href: str # Stylesheet URL
36
title: str # Advisory title
37
disabled: bool # Disabled state
38
encoding: str # Character encoding
39
namespaces: dict # Namespace declarations
40
variables: 'CSSVariablesDeclaration' # CSS variables
41
42
# Rule Management
43
def insertRule(rule, index):
44
"""
45
Insert CSS rule at specified index.
46
47
Parameters:
48
- rule (str/CSSRule): CSS rule text or rule object
49
- index (int): Position to insert rule
50
51
Returns:
52
int: Index where rule was inserted
53
"""
54
55
def deleteRule(index):
56
"""
57
Delete rule at specified index.
58
59
Parameters:
60
- index (int): Index of rule to delete
61
"""
62
63
def add(rule):
64
"""
65
Add CSS rule to end of stylesheet.
66
67
Parameters:
68
- rule (str/CSSRule): CSS rule text or rule object
69
70
Returns:
71
int: Index where rule was added
72
"""
73
74
# Serialization
75
@property
76
def cssText():
77
"""Complete CSS text representation of stylesheet"""
78
79
@cssText.setter
80
def cssText(cssText):
81
"""Set stylesheet content from CSS text"""
82
```
83
84
### CSSRuleList Class
85
86
Ordered collection of CSS rules within a stylesheet or nested rule.
87
88
```python { .api }
89
class CSSRuleList:
90
"""
91
Ordered list of CSS rules implementing DOM Level 2 CSSRuleList.
92
"""
93
94
# Properties
95
length: int # Number of rules in list
96
97
# Access Methods
98
def item(index):
99
"""
100
Get rule at specified index.
101
102
Parameters:
103
- index (int): Rule index (0-based)
104
105
Returns:
106
CSSRule: Rule at index, or None if out of bounds
107
"""
108
109
def __getitem__(index):
110
"""Get rule by index using bracket notation"""
111
112
def __len__():
113
"""Get number of rules"""
114
115
def __iter__():
116
"""Iterator over rules"""
117
118
# Modification Methods
119
def append(rule):
120
"""Add rule to end of list"""
121
122
def insert(index, rule):
123
"""Insert rule at specified index"""
124
125
def extend(rules):
126
"""Add multiple rules to end of list"""
127
```
128
129
### StyleSheet Base Class
130
131
Base class for all stylesheet types implementing DOM Level 2 StyleSheet interface.
132
133
```python { .api }
134
class StyleSheet:
135
"""
136
Base stylesheet class implementing DOM Level 2 StyleSheet interface.
137
"""
138
139
# Properties
140
type: str # MIME type (always 'text/css' for CSS)
141
disabled: bool # Whether stylesheet is disabled
142
ownerNode # DOM node that owns this stylesheet
143
parentStyleSheet # Parent stylesheet for imported sheets
144
href: str # URL of stylesheet
145
title: str # Advisory title
146
media: 'MediaList' # Media query list
147
```
148
149
### StyleSheetList Class
150
151
Collection of stylesheets implementing DOM Level 2 StyleSheetList interface.
152
153
```python { .api }
154
class StyleSheetList:
155
"""
156
List of stylesheets implementing DOM Level 2 StyleSheetList.
157
"""
158
159
# Properties
160
length: int # Number of stylesheets
161
162
# Access Methods
163
def item(index):
164
"""
165
Get stylesheet at specified index.
166
167
Parameters:
168
- index (int): Stylesheet index
169
170
Returns:
171
StyleSheet: Stylesheet at index
172
"""
173
174
def __getitem__(index):
175
"""Get stylesheet by index using bracket notation"""
176
177
def __len__():
178
"""Get number of stylesheets"""
179
```
180
181
### MediaList Class
182
183
Media query list for controlling stylesheet applicability.
184
185
```python { .api }
186
class MediaList:
187
"""
188
Media query list implementing DOM Level 2 MediaList interface.
189
"""
190
191
# Properties
192
mediaText: str # Complete media query string
193
length: int # Number of media queries
194
195
# Access Methods
196
def item(index):
197
"""Get media query at index"""
198
199
def __getitem__(index):
200
"""Get media query by index"""
201
202
# Modification Methods
203
def appendMedium(newMedium):
204
"""
205
Add media query to list.
206
207
Parameters:
208
- newMedium (str): Media query to add
209
"""
210
211
def deleteMedium(oldMedium):
212
"""
213
Remove media query from list.
214
215
Parameters:
216
- oldMedium (str): Media query to remove
217
"""
218
```
219
220
### MediaQuery Class
221
222
Individual media query with features and conditions.
223
224
```python { .api }
225
class MediaQuery:
226
"""
227
Individual media query with type and feature conditions.
228
"""
229
230
# Properties
231
mediaText: str # Complete media query text
232
mediaType: str # Media type (screen, print, etc.)
233
234
# Methods
235
def __str__():
236
"""String representation of media query"""
237
```
238
239
## Usage Examples
240
241
### Creating and Manipulating Stylesheets
242
243
```python
244
import cssutils
245
from cssutils.css import CSSStyleSheet, CSSStyleRule
246
247
# Create new stylesheet
248
sheet = CSSStyleSheet()
249
250
# Add rules
251
sheet.add('body { margin: 0; padding: 0; }')
252
sheet.insertRule('h1 { color: blue; }', 0)
253
254
# Access rules
255
for rule in sheet.cssRules:
256
print(f"Rule: {rule.cssText}")
257
258
# Create rule programmatically
259
rule = CSSStyleRule()
260
rule.selectorText = 'p'
261
rule.style.color = 'red'
262
rule.style.fontSize = '14px'
263
sheet.add(rule)
264
265
print(sheet.cssText)
266
```
267
268
### Working with Media Queries
269
270
```python
271
import cssutils
272
273
# Parse stylesheet with media queries
274
css = """
275
@media screen and (max-width: 768px) {
276
body { font-size: 14px; }
277
}
278
@media print {
279
body { font-size: 12pt; }
280
}
281
"""
282
283
sheet = cssutils.parseString(css)
284
285
# Access media rules
286
for rule in sheet:
287
if rule.type == rule.MEDIA_RULE:
288
print(f"Media: {rule.media.mediaText}")
289
for nested_rule in rule.cssRules:
290
print(f" {nested_rule.cssText}")
291
292
# Create stylesheet with media restrictions
293
sheet = CSSStyleSheet(media='screen, print')
294
print(f"Stylesheet media: {sheet.media.mediaText}")
295
296
# Modify media list
297
sheet.media.appendMedium('handheld')
298
sheet.media.deleteMedium('print')
299
```
300
301
### Namespace Handling
302
303
```python
304
import cssutils
305
306
# CSS with namespaces
307
css = """
308
@namespace svg "http://www.w3.org/2000/svg";
309
@namespace html "http://www.w3.org/1999/xhtml";
310
311
svg|rect { fill: blue; }
312
html|div { color: red; }
313
"""
314
315
sheet = cssutils.parseString(css)
316
317
# Access namespace declarations
318
for prefix, uri in sheet.namespaces.items():
319
print(f"Namespace {prefix}: {uri}")
320
321
# Add namespace programmatically
322
sheet.namespaces['custom'] = 'http://example.com/ns'
323
```
324
325
### Stylesheet Properties and Metadata
326
327
```python
328
import cssutils
329
330
# Create stylesheet with metadata
331
sheet = cssutils.parseString(
332
'body { color: red; }',
333
href='http://example.com/styles.css',
334
media='screen',
335
title='Main Styles'
336
)
337
338
# Access properties
339
print(f"URL: {sheet.href}")
340
print(f"Title: {sheet.title}")
341
print(f"Media: {sheet.media.mediaText}")
342
print(f"Encoding: {sheet.encoding}")
343
print(f"Number of rules: {len(sheet.cssRules)}")
344
345
# Modify properties
346
sheet.disabled = True
347
sheet.title = 'Updated Styles'
348
```
349
350
### Rule Management
351
352
```python
353
import cssutils
354
355
sheet = cssutils.parseString("""
356
body { margin: 0; }
357
h1 { color: blue; }
358
p { font-size: 14px; }
359
""")
360
361
# Insert rule at beginning
362
sheet.insertRule('* { box-sizing: border-box; }', 0)
363
364
# Delete specific rule
365
sheet.deleteRule(2) # Remove h1 rule
366
367
# Add rule at end
368
sheet.add('.highlight { background: yellow; }')
369
370
# Count and iterate
371
print(f"Total rules: {len(sheet.cssRules)}")
372
for i, rule in enumerate(sheet.cssRules):
373
print(f"Rule {i}: {rule.cssText}")
374
```