CSS Beautifier
A Python library for unobfuscating and beautifying CSS code, improving readability and maintainability. It is currently at version 1.15.4 and is part of the larger `js-beautify` project, with releases tied to its development cycle. The library provides programmatic access to format CSS strings or files with configurable options.
Warnings
- breaking Past versions (e.g., v1.11.0) experienced `pip install cssbeautifier` failures due to packaging issues related to the `jsbeautifier` dependency. While fixed in later releases (v1.12.0), this highlights a potential fragility in the dependency management.
- gotcha The Python `cssbeautifier` library is specifically designed for CSS code and *does not* support HTML beautification. Users familiar with the Node.js version of the beautifier might expect HTML support, but this functionality is not available in the Python package.
- gotcha The beautifier may produce unexpected results or even invalid CSS for highly complex, unconventional, or malformed CSS syntax. Historical issues include incorrect handling of `@media` queries, `@font-face` rules, nested `@-rules`, and comments with quotes, leading to extra spaces or parsing errors.
- gotcha When configuring options, the Python API uses `snake_case` for option names (e.g., `indent_size`), while the command-line interface (CLI) and some other language implementations (e.g., Node.js) typically use `kebab-case` (e.g., `--indent-size`).
Install
-
pip install cssbeautifier
Imports
- beautify
import cssbeautifier result = cssbeautifier.beautify(css_string)
- default_options
from cssbeautifier import default_options opts = default_options()
Quickstart
import cssbeautifier
ugly_css = ".container{display:flex;}.item{color:red;font-size:16px;margin:0 auto;}"
# Beautify with default options
pretty_css_default = cssbeautifier.beautify(ugly_css)
print("--- Default Beautification ---")
print(pretty_css_default)
# Beautify with custom options
opts = cssbeautifier.default_options()
opts.indent_size = 2
opts.end_with_newline = True
opts.newline_between_rules = False
pretty_css_custom = cssbeautifier.beautify(ugly_css, opts)
print("\n--- Custom Beautification (2-space indent, no newline between rules) ---")
print(pretty_css_custom)
# Example of beautifying a file (conceptual, requires a file to exist)
# Assuming 'styles.min.css' exists with ugly_css content
# with open('styles.min.css', 'w') as f:
# f.write(ugly_css)
# beautified_file_content = cssbeautifier.beautify_file('styles.min.css', opts)
# print("\n--- Beautified File Content ---")
# print(beautified_file_content)