How to Work with the CSSOM in Python

How to Work with the CSSOM in Python

Aspose.HTML FOSS for Python implements the CSS object model: stylesheets parse into live rule objects, attach to documents, and resolve through a real cascade. This guide styles an element and reads the computed result, using pip for installation.

Step-by-Step Guide

Step 1: Install the Package

pip install aspose-html-foss

Step 2: Import Required Classes

from aspose_html.dom import Document
from aspose_html.cssom import CSSStyleSheet

Step 3: Build a Styled Element

Create a document and an element with a class and an id — both will participate in selector matching:

doc = Document()
el = doc.create_element("div")
el.set_attribute("class", "foo")
el.set_attribute("id", "bar")
doc.append_child(el)

Step 4: Parse and Attach a Stylesheet

replace_sync() parses stylesheet text; attach_style_sheet() registers it with the document:

sheet = CSSStyleSheet()
sheet.replace_sync(".foo { color: red } #bar { color: blue }")
doc.attach_style_sheet(sheet)

Step 5: Read the Computed Style

The ID selector (specificity 1,0,0) outranks the class selector (0,1,0), so blue wins:

style = el.get_computed_style()
print(style.get_property_value("color"))

Common Issues and Fixes

The computed value ignores my stylesheet. The sheet must be attached via Document.attach_style_sheet() before get_computed_style() is called.

An inline style loses to a stylesheet rule. Author rules marked !important outrank non-important inline declarations; inspect priorities with get_property_priority().

Two rules with the same specificity give a surprising winner. Later rules win equal-specificity ties — rule order inside the sheet matters.

Frequently Asked Questions

How do I set inline styles programmatically?

Through the element’s style declaration: assign it to a variable and call set_property() on it.

What object does get_computed_style return?

A ComputedStyleDeclaration; read values with get_property_value().

Are media, keyframes, and font-face rules modelled?

Yes — parsed sheets contain typed rules including CSSMediaRule, CSSKeyframesRule, and CSSFontFaceRule in a CSSRuleList.

See Also