dict2css
dict2css is a μ-library for constructing cascading style sheets from Python dictionaries. It simplifies the process of programmatically generating CSS by mapping Python dictionary structures to CSS rules. The current version is 0.3.0.post1, with an irregular release cadence, having recent updates in late 2023.
Warnings
- gotcha The `make_css` convenience function was introduced in `v0.3.0` as the primary, simpler interface for converting dictionaries. While `DictionaryToCss` class still works, new code should prefer `make_css`.
- gotcha The library primarily supports basic element, class, and ID selectors with nested properties. It does not natively provide direct dictionary-based support for complex CSS features like pseudo-classes (`:hover`), pseudo-elements (`::before`), or media queries (`@media`) within the standard nested dictionary structure.
- gotcha dict2css performs minimal validation on the *values* provided in the input dictionary. Supplying syntactically incorrect or semantically invalid CSS property values (e.g., specifying a non-existent color or unit) will result in invalid CSS being generated without explicit errors from the library itself.
Install
-
pip install dict2css
Imports
- make_css
from dict2css import make_css
- DictionaryToCss
from dict2css import DictionaryToCss
Quickstart
from dict2css import make_css
# Define your CSS structure as a Python dictionary
style_dict = {
"body": {
"font-family": "'Arial', sans-serif",
"margin": "0",
"padding": "0",
"background-color": "#f0f0f0"
},
"h1": {
"color": "#333",
"text-align": "center"
},
"p": {
"font-size": "16px",
"line-height": "1.5",
"color": "#666"
},
"#main-content": {
"width": "80%",
"margin": "20px auto",
"padding": "20px",
"background": "#fff",
"border-radius": "8px"
}
}
# Convert the dictionary to a CSS string
css_output = make_css(style_dict)
print(css_output)