Tinycss2

1.5.1 · active · verified Sat Mar 28

tinycss2 is a low-level CSS parser and generator written in Python. It can parse CSS strings, return objects representing tokens and blocks, and generate CSS strings from these objects. Based on the CSS Syntax Level 3 specification, it handles the grammar of CSS but does not know specific rules, properties, or values. It is actively maintained with regular releases.

Warnings

Install

Imports

Quickstart

Parses a CSS string into an Abstract Syntax Tree (AST) of tokens and blocks, then iterates through the parsed rules and declarations.

import tinycss2

css_input = '#my-id div { width: 50%; height: 100px }'
rules = tinycss2.parse_stylesheet(css_input)

# The parsed output is a list of nodes
for rule in rules:
    if rule.type == 'qualified-rule':
        print(f"Qualified Rule: {rule.prelude[0].value} {rule.prelude[2].value}") # Example: 'my-id', 'div'
        for declaration in tinycss2.parse_declaration_list(rule.content):
            if declaration.type == 'declaration':
                print(f"  Declaration: {declaration.name}: {declaration.value[0].value}{declaration.value[0].unit}")

# To serialize back to CSS (approximate)
serialized_css = ''.join(node.serialize() for node in rules)
print(f"\nSerialized CSS: {serialized_css}")

view raw JSON →