A CSS Cascading Style Sheets library for Python implementing DOM Level 2 Style specifications
—
CSS stylesheet management implementing DOM Level 2 Style Sheets specification. Create, manipulate, and manage complete CSS stylesheets with rules, media queries, namespaces, and variables.
Main stylesheet container representing a complete CSS document with all rules and metadata.
class CSSStyleSheet:
"""
CSS stylesheet implementing DOM Level 2 CSSStyleSheet interface.
Constructor:
CSSStyleSheet(href=None, media=None, title='', disabled=None,
ownerNode=None, parentStyleSheet=None, readonly=False,
ownerRule=None, validating=True)
Parameters:
- href (str): URL of the stylesheet
- media (str/MediaList): Media query list for stylesheet applicability
- title (str): Advisory title for the stylesheet
- disabled (bool): Whether stylesheet is disabled
- ownerNode: DOM node that owns this stylesheet
- parentStyleSheet: Parent stylesheet for imported sheets
- readonly (bool): Whether stylesheet can be modified
- ownerRule: CSS rule that imported this stylesheet
- validating (bool): Whether to validate modifications
"""
# Properties
cssRules: 'CSSRuleList' # All rules in the stylesheet
media: 'MediaList' # Media query list
href: str # Stylesheet URL
title: str # Advisory title
disabled: bool # Disabled state
encoding: str # Character encoding
namespaces: dict # Namespace declarations
variables: 'CSSVariablesDeclaration' # CSS variables
# Rule Management
def insertRule(rule, index):
"""
Insert CSS rule at specified index.
Parameters:
- rule (str/CSSRule): CSS rule text or rule object
- index (int): Position to insert rule
Returns:
int: Index where rule was inserted
"""
def deleteRule(index):
"""
Delete rule at specified index.
Parameters:
- index (int): Index of rule to delete
"""
def add(rule):
"""
Add CSS rule to end of stylesheet.
Parameters:
- rule (str/CSSRule): CSS rule text or rule object
Returns:
int: Index where rule was added
"""
# Serialization
@property
def cssText():
"""Complete CSS text representation of stylesheet"""
@cssText.setter
def cssText(cssText):
"""Set stylesheet content from CSS text"""Ordered collection of CSS rules within a stylesheet or nested rule.
class CSSRuleList:
"""
Ordered list of CSS rules implementing DOM Level 2 CSSRuleList.
"""
# Properties
length: int # Number of rules in list
# Access Methods
def item(index):
"""
Get rule at specified index.
Parameters:
- index (int): Rule index (0-based)
Returns:
CSSRule: Rule at index, or None if out of bounds
"""
def __getitem__(index):
"""Get rule by index using bracket notation"""
def __len__():
"""Get number of rules"""
def __iter__():
"""Iterator over rules"""
# Modification Methods
def append(rule):
"""Add rule to end of list"""
def insert(index, rule):
"""Insert rule at specified index"""
def extend(rules):
"""Add multiple rules to end of list"""Base class for all stylesheet types implementing DOM Level 2 StyleSheet interface.
class StyleSheet:
"""
Base stylesheet class implementing DOM Level 2 StyleSheet interface.
"""
# Properties
type: str # MIME type (always 'text/css' for CSS)
disabled: bool # Whether stylesheet is disabled
ownerNode # DOM node that owns this stylesheet
parentStyleSheet # Parent stylesheet for imported sheets
href: str # URL of stylesheet
title: str # Advisory title
media: 'MediaList' # Media query listCollection of stylesheets implementing DOM Level 2 StyleSheetList interface.
class StyleSheetList:
"""
List of stylesheets implementing DOM Level 2 StyleSheetList.
"""
# Properties
length: int # Number of stylesheets
# Access Methods
def item(index):
"""
Get stylesheet at specified index.
Parameters:
- index (int): Stylesheet index
Returns:
StyleSheet: Stylesheet at index
"""
def __getitem__(index):
"""Get stylesheet by index using bracket notation"""
def __len__():
"""Get number of stylesheets"""Media query list for controlling stylesheet applicability.
class MediaList:
"""
Media query list implementing DOM Level 2 MediaList interface.
"""
# Properties
mediaText: str # Complete media query string
length: int # Number of media queries
# Access Methods
def item(index):
"""Get media query at index"""
def __getitem__(index):
"""Get media query by index"""
# Modification Methods
def appendMedium(newMedium):
"""
Add media query to list.
Parameters:
- newMedium (str): Media query to add
"""
def deleteMedium(oldMedium):
"""
Remove media query from list.
Parameters:
- oldMedium (str): Media query to remove
"""Individual media query with features and conditions.
class MediaQuery:
"""
Individual media query with type and feature conditions.
"""
# Properties
mediaText: str # Complete media query text
mediaType: str # Media type (screen, print, etc.)
# Methods
def __str__():
"""String representation of media query"""import cssutils
from cssutils.css import CSSStyleSheet, CSSStyleRule
# Create new stylesheet
sheet = CSSStyleSheet()
# Add rules
sheet.add('body { margin: 0; padding: 0; }')
sheet.insertRule('h1 { color: blue; }', 0)
# Access rules
for rule in sheet.cssRules:
print(f"Rule: {rule.cssText}")
# Create rule programmatically
rule = CSSStyleRule()
rule.selectorText = 'p'
rule.style.color = 'red'
rule.style.fontSize = '14px'
sheet.add(rule)
print(sheet.cssText)import cssutils
# Parse stylesheet with media queries
css = """
@media screen and (max-width: 768px) {
body { font-size: 14px; }
}
@media print {
body { font-size: 12pt; }
}
"""
sheet = cssutils.parseString(css)
# Access media rules
for rule in sheet:
if rule.type == rule.MEDIA_RULE:
print(f"Media: {rule.media.mediaText}")
for nested_rule in rule.cssRules:
print(f" {nested_rule.cssText}")
# Create stylesheet with media restrictions
sheet = CSSStyleSheet(media='screen, print')
print(f"Stylesheet media: {sheet.media.mediaText}")
# Modify media list
sheet.media.appendMedium('handheld')
sheet.media.deleteMedium('print')import cssutils
# CSS with namespaces
css = """
@namespace svg "http://www.w3.org/2000/svg";
@namespace html "http://www.w3.org/1999/xhtml";
svg|rect { fill: blue; }
html|div { color: red; }
"""
sheet = cssutils.parseString(css)
# Access namespace declarations
for prefix, uri in sheet.namespaces.items():
print(f"Namespace {prefix}: {uri}")
# Add namespace programmatically
sheet.namespaces['custom'] = 'http://example.com/ns'import cssutils
# Create stylesheet with metadata
sheet = cssutils.parseString(
'body { color: red; }',
href='http://example.com/styles.css',
media='screen',
title='Main Styles'
)
# Access properties
print(f"URL: {sheet.href}")
print(f"Title: {sheet.title}")
print(f"Media: {sheet.media.mediaText}")
print(f"Encoding: {sheet.encoding}")
print(f"Number of rules: {len(sheet.cssRules)}")
# Modify properties
sheet.disabled = True
sheet.title = 'Updated Styles'import cssutils
sheet = cssutils.parseString("""
body { margin: 0; }
h1 { color: blue; }
p { font-size: 14px; }
""")
# Insert rule at beginning
sheet.insertRule('* { box-sizing: border-box; }', 0)
# Delete specific rule
sheet.deleteRule(2) # Remove h1 rule
# Add rule at end
sheet.add('.highlight { background: yellow; }')
# Count and iterate
print(f"Total rules: {len(sheet.cssRules)}")
for i, rule in enumerate(sheet.cssRules):
print(f"Rule {i}: {rule.cssText}")Install with Tessl CLI
npx tessl i tessl/pypi-cssutils