Tinycss2
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
- deprecated The `tinycss2.parse_declaration_list` function was deprecated in v1.3.0.
- breaking Python 3.6 support was dropped in v1.2.0, and Python 3.5 support in v1.1.0. The library currently requires Python 3.10 or newer.
- gotcha tinycss2 is a low-level CSS parser. It understands CSS syntax (tokens, blocks, qualified rules, at-rules) but does not interpret the semantics of specific CSS properties, values, or selectors. It does not provide high-level representations of browser-rendered styles.
- breaking In tinycss2 v0.5, the default behavior for parsing functions changed to preserve CSS comments and top-level whitespace in the output AST. Previously, these were skipped by default.
Install
-
pip install tinycss2
Imports
- parse_stylesheet
import tinycss2 rules = tinycss2.parse_stylesheet('body { color: red; }') - ast nodes (e.g., QualifiedRule, IdentToken)
from tinycss2.ast import QualifiedRule, IdentToken
Quickstart
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}")