CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-cssutils

A CSS Cascading Style Sheets library for Python implementing DOM Level 2 Style specifications

Pending
Overview
Eval results
Files

style-declarations.mddocs/

Style Declarations

Manage CSS property declarations with validation, shorthand expansion, value parsing, and complete support for CSS property manipulation within rules.

Capabilities

CSSStyleDeclaration Class

Container for CSS property declarations implementing DOM Level 2 CSSStyleDeclaration interface.

class CSSStyleDeclaration:
    """
    CSS property declarations container implementing DOM Level 2 CSSStyleDeclaration.
    
    Constructor:
    CSSStyleDeclaration(cssText='', parentRule=None, readonly=False, validating=True)
    
    Parameters:
    - cssText (str): Initial CSS declarations text
    - parentRule: Parent CSS rule that owns this declaration
    - readonly (bool): Whether declarations can be modified
    - validating (bool): Whether to validate property names and values
    """
    
    # Properties
    cssText: str    # Complete CSS text of all declarations
    length: int     # Number of property declarations
    parentRule      # Parent CSS rule
    
    # Property Access Methods
    def getPropertyValue(propertyName):
        """
        Get property value by name.
        
        Parameters:
        - propertyName (str): CSS property name
        
        Returns:
        str: Property value, or empty string if not set
        """
    
    def getPropertyPriority(propertyName):
        """
        Get property priority (!important).
        
        Parameters:
        - propertyName (str): CSS property name
        
        Returns:
        str: 'important' if !important is set, empty string otherwise
        """
    
    def setProperty(propertyName, value, priority=''):
        """
        Set property value and priority.
        
        Parameters:
        - propertyName (str): CSS property name
        - value (str): CSS property value
        - priority (str): Priority ('important' or empty string)
        """
    
    def removeProperty(propertyName):
        """
        Remove property from declarations.
        
        Parameters:
        - propertyName (str): CSS property name to remove
        
        Returns:
        str: Previous value of removed property
        """
    
    def item(index):
        """
        Get property name at index.
        
        Parameters:
        - index (int): Property index (0-based)
        
        Returns:
        str: Property name at index
        """
    
    # Property Collection Methods
    def getProperties(all=False):
        """
        Get list of Property objects.
        
        Parameters:
        - all (bool): If True, include all properties including duplicates and invalid
        
        Returns:
        list: List of Property objects
        """
    
    def keys():
        """
        Get list of property names.
        
        Returns:
        list: List of property names
        """
    
    # Iteration Support
    def __getitem__(index):
        """Get property name by index"""
    
    def __len__():
        """Get number of properties"""
    
    def __iter__():
        """Iterator over property names"""
    
    # CSS Text Methods
    @property
    def cssText():
        """Get/set complete CSS declarations text"""
    
    @cssText.setter
    def cssText(cssText):
        """Set declarations from CSS text"""

Property Class

Individual CSS property with name, value, and priority.

class Property:
    """
    Individual CSS property within a CSSStyleDeclaration.
    """
    
    # Properties
    name: str                    # Property name (normalized)
    value: str                   # Property value text
    priority: str                # Priority ('important' or empty)
    propertyValue: 'PropertyValue'  # Parsed property value object
    
    # Methods
    @property
    def name():
        """Get/set property name"""
    
    @name.setter
    def name(name):
        """Set property name with normalization"""
    
    @property
    def value():
        """Get/set property value text"""
    
    @value.setter
    def value(value):
        """Set property value with parsing"""
    
    @property
    def priority():
        """Get/set property priority"""
    
    @priority.setter
    def priority(priority):
        """Set property priority ('important' or empty)"""

PropertyValue Class

Structured representation of CSS property values with individual value components.

class PropertyValue:
    """
    Container for CSS property values with structured access to components.
    """
    
    # Properties
    cssText: str  # Complete property value text
    length: int   # Number of value components
    
    # Value Access Methods
    def item(index):
        """
        Get value component at index.
        
        Parameters:
        - index (int): Value component index
        
        Returns:
        Value: Value component at index
        """
    
    def __getitem__(index):
        """Get value component by index"""
    
    def __len__():
        """Get number of value components"""
    
    def __iter__():
        """Iterator over value components"""
    
    # Value Manipulation
    def append(value):
        """Add value component to end"""
    
    def insert(index, value):
        """Insert value component at index"""
    
    def extend(values):
        """Add multiple value components"""

Value Classes

Specific value types for different CSS value categories.

class Value:
    """Base class for CSS values"""
    
    # Properties
    type: str     # Value type identifier
    cssText: str  # CSS text representation
    value: str    # Normalized value
    
class ColorValue:
    """CSS color value (named colors, hex, rgb(), hsl(), etc.)"""
    
    # Properties
    type: str = 'COLOR'
    red: int      # Red component (0-255)
    green: int    # Green component (0-255) 
    blue: int     # Blue component (0-255)
    alpha: float  # Alpha component (0.0-1.0)

class DimensionValue:
    """CSS dimensional value (length, percentage, angle, time, frequency)"""
    
    # Properties
    type: str = 'DIMENSION'
    value: float  # Numeric value
    dimension: str  # Unit (px, em, %, deg, s, Hz, etc.)

class URIValue:
    """CSS URI value (url())"""
    
    # Properties
    type: str = 'URI'
    uri: str      # URI string (without url() wrapper)
    
class CSSFunction:
    """CSS function value (rgb(), calc(), etc.)"""
    
    # Properties
    type: str = 'FUNCTION'
    functionName: str    # Function name
    arguments: list      # Function arguments as Value objects

class CSSVariable:
    """CSS variable reference (var())"""
    
    # Properties
    type: str = 'VARIABLE'
    name: str           # Variable name
    fallback: 'Value'   # Fallback value (optional)

Usage Examples

Basic Property Management

import cssutils
from cssutils.css import CSSStyleDeclaration

# Create style declaration
style = CSSStyleDeclaration()

# Set properties
style.setProperty('color', 'red')
style.setProperty('font-size', '16px')
style.setProperty('margin', '10px 20px', 'important')

print(f"CSS Text: {style.cssText}")
print(f"Number of properties: {len(style)}")

# Get property values
color = style.getPropertyValue('color')
priority = style.getPropertyPriority('margin')
print(f"Color: {color}")
print(f"Margin priority: {priority}")

# Remove property
old_value = style.removeProperty('font-size')
print(f"Removed font-size: {old_value}")

Working with CSS Rules

import cssutils

# Parse CSS with properties
css = """
h1 {
    color: #333;
    font-size: 24px;
    margin: 0 0 1em 0;
    font-weight: bold !important;
}
"""

sheet = cssutils.parseString(css)
rule = sheet.cssRules[0]  # Get first rule

# Access style declaration
style = rule.style
print(f"Rule properties: {style.cssText}")

# Iterate over properties
for i in range(len(style)):
    prop_name = style.item(i)
    prop_value = style.getPropertyValue(prop_name)
    prop_priority = style.getPropertyPriority(prop_name)
    print(f"{prop_name}: {prop_value} {prop_priority}")

# Modify properties
style.setProperty('line-height', '1.5')
style.setProperty('color', 'blue')
print(f"Modified: {style.cssText}")

Property Object Access

import cssutils

# Parse CSS with various properties
css = """
.example {
    color: red;
    background: url('bg.jpg') no-repeat center;
    margin: 10px 20px;
    font-weight: bold !important;
}
"""

sheet = cssutils.parseString(css)
style = sheet.cssRules[0].style

# Get Property objects
properties = style.getProperties()
for prop in properties:
    print(f"Property: {prop.name}")
    print(f"  Value: {prop.value}")
    print(f"  Priority: {prop.priority}")
    print(f"  PropertyValue type: {type(prop.propertyValue)}")
    
    # Access structured property values
    for i, value in enumerate(prop.propertyValue):
        print(f"    Value {i}: {value.cssText} (type: {value.type})")

Shorthand Property Handling

import cssutils

# CSS with shorthand properties
css = """
.box {
    margin: 10px 20px 30px 40px;
    padding: 15px 25px;
    border: 2px solid red;
    background: #fff url('bg.png') no-repeat center top;
    font: bold 16px/1.5 Arial, sans-serif;
}
"""

sheet = cssutils.parseString(css)
style = sheet.cssRules[0].style

# Access shorthand properties
print("Shorthand properties:")
for prop in style.getProperties():
    print(f"{prop.name}: {prop.value}")
    
    # Examine property value components
    if len(prop.propertyValue) > 1:
        print(f"  Components ({len(prop.propertyValue)}):")
        for i, value in enumerate(prop.propertyValue):
            print(f"    {i}: {value.cssText}")

# Set shorthand property
style.setProperty('border', '1px dashed blue')
print(f"\nAfter modification: {style.cssText}")

Value Type Analysis

import cssutils
from cssutils.css import ColorValue, DimensionValue, URIValue

# CSS with different value types
css = """
.demo {
    color: rgb(255, 0, 0);
    width: 300px;
    height: 75%;
    background-image: url('image.jpg');
    transform: rotate(45deg);
    transition-duration: 0.3s;
}
"""

sheet = cssutils.parseString(css)
style = sheet.cssRules[0].style

# Analyze value types
for prop in style.getProperties():
    print(f"\nProperty: {prop.name}")
    
    for value in prop.propertyValue:
        print(f"  Value: {value.cssText}")
        print(f"  Type: {value.type}")
        
        # Handle specific value types
        if isinstance(value, ColorValue):
            print(f"    RGB: ({value.red}, {value.green}, {value.blue})")
            if hasattr(value, 'alpha'):
                print(f"    Alpha: {value.alpha}")
        elif isinstance(value, DimensionValue):
            print(f"    Number: {value.value}")
            print(f"    Unit: {value.dimension}")
        elif isinstance(value, URIValue):
            print(f"    URI: {value.uri}")

Property Validation

import cssutils

# Enable validation
parser = cssutils.CSSParser(validate=True)

# Valid CSS
valid_css = """
.valid {
    color: red;
    margin: 10px;
    display: block;
}
"""

# Invalid CSS
invalid_css = """
.invalid {
    color: notacolor;
    margin: invalidvalue;
    unknown-property: somevalue;
}
"""

# Parse with validation
print("Parsing valid CSS:")
valid_sheet = parser.parseString(valid_css)
print(f"Rules: {len(valid_sheet.cssRules)}")

print("\nParsing invalid CSS:")
invalid_sheet = parser.parseString(invalid_css)
print(f"Rules: {len(invalid_sheet.cssRules)}")

# Check individual properties
if invalid_sheet.cssRules:
    style = invalid_sheet.cssRules[0].style
    for prop in style.getProperties(all=True):  # Include invalid properties
        print(f"Property: {prop.name} = {prop.value}")

CSS Variables Support

import cssutils

# CSS with custom properties (variables)
css = """
:root {
    --main-color: #333;
    --main-font: Arial, sans-serif;
    --spacing: 20px;
}

.component {
    color: var(--main-color);
    font-family: var(--main-font);
    margin: var(--spacing);
    padding: var(--spacing, 10px); /* with fallback */
}
"""

sheet = cssutils.parseString(css)

# Access variable declarations
for rule in sheet:
    if rule.type == rule.STYLE_RULE:
        print(f"Selector: {rule.selectorText}")
        style = rule.style
        
        for prop in style.getProperties():
            print(f"  {prop.name}: {prop.value}")
            
            # Look for variable references
            for value in prop.propertyValue:
                if hasattr(value, 'type') and value.type == 'VARIABLE':
                    print(f"    Variable: {value.name}")
                    if hasattr(value, 'fallback') and value.fallback:
                        print(f"    Fallback: {value.fallback.cssText}")

Install with Tessl CLI

npx tessl i tessl/pypi-cssutils

docs

css-rules.md

index.md

parsing.md

selectors.md

serialization.md

style-declarations.md

stylesheets.md

utilities.md

tile.json