Installation
pip install cssbeautifier
The cssbeautifier package is separate from jsbeautifier. You need to install it independently even if you already have jsbeautifier installed.
cssbeautifier depends on jsbeautifier internally and will install it as a dependency automatically.
Module
Functions
beautify()
Beautify a CSS source string.
cssbeautifier.beautify(source: str, opts=None) -> str
The CSS source code string to beautify.
An options object returned by default_options(). If omitted, default options are used.
The beautified CSS source code.
beautify_file()
Read a CSS file and return beautified output as a string.
cssbeautifier.beautify_file(file_name: str, opts=None) -> str
Path to the CSS file. Pass "-" to read from stdin.
An options object returned by default_options().
The beautified CSS source code.
default_options()
Return a BeautifierOptions instance populated with default values.
cssbeautifier.default_options() -> BeautifierOptions
A BeautifierOptions object. Mutate its attributes before passing to beautify() or beautify_file().
BeautifierOptions attributes
Number of spaces per indentation level.
Character used for indentation.
Indent with tabs instead of spaces.
Line terminator character(s). auto uses the first newline found in the input, or \n if none is found.
Ensure the output ends with a newline.
Brace placement: collapse (opening brace on same line as selector) or expand (opening brace on its own line).
selector_separator_newline
Print each selector in a multi-selector rule on its own line.
Add a blank line between CSS rules.
Add spaces around CSS combinators such as >, ~, and +.
Keep indentation whitespace on otherwise empty lines.
Examples
import cssbeautifier
# Beautify with default options
result = cssbeautifier.beautify('.container{display:flex;}.item{color:red;}')
print(result)
# .container {
# display: flex;
# }
#
# .item {
# color: red;
# }
# Beautify with custom options
opts = cssbeautifier.default_options()
opts.indent_size = 2
opts.end_with_newline = True
opts.newline_between_rules = True
result = cssbeautifier.beautify(
'h1,h2,h3{font-weight:bold;margin:0}',
opts
)
print(result)
# h1,
# h2,
# h3 {
# font-weight: bold;
# margin: 0
# }
# Beautify a file
result = cssbeautifier.beautify_file('styles.min.css')
with open('styles.css', 'w') as f:
f.write(result)
# Read from stdin
import sys
result = cssbeautifier.beautify_file('-') # reads from stdin
sys.stdout.write(result)
CLI (Python)
The cssbeautifier package also installs a css-beautify command:
# Beautify a file
css-beautify styles.min.css
# Specify options
css-beautify -s 2 --end-with-newline styles.min.css
# Replace in-place
css-beautify -r styles.min.css
# Write to a specific output file
css-beautify -o styles.css styles.min.css
# Disable newline between rules
css-beautify --disable-newline-between-rules styles.css
# Add spaces around combinators
css-beautify --space-around-combinator styles.css
Run css-beautify --help for a full list of CLI flags.