Overview
The CSS beautifier is available as a named export from the js-beautify package:
const beautify = require ( 'js-beautify' ). css ;
const beautify = require ( 'js-beautify' ). css_beautify ; // legacy alias
For ESM imports:
import beautify from 'js-beautify' ;
beautify . css ( code , options );
Function signature
beautify . css ( sourceCode : string , options ?: object ): string
Parameters
The CSS source code string to beautify.
Configuration options object. All keys use underscores. Number of spaces per indentation level.
Character used for indentation. Overridden to \t when indent_with_tabs is true.
Indent with tabs instead of spaces.
Line terminator character(s). auto uses the first newline found in the input file, or \n if none is found. Accepts \n, \r\n, or \r.
Ensure the output ends with a newline character.
Controls brace placement. CSS supports collapse and expand. collapse keeps the opening brace on the same line as the selector; expand places it on its own line.
selector_separator_newline
Print each selector in a multi-selector rule on its own line.
Add an empty line between CSS rules.
Add spaces around CSS combinators such as >, ~, and +.
Keep indentation whitespace on otherwise empty lines.
Return value
The beautified CSS source code as a string.
Examples
const beautifyCss = require ( 'js-beautify' ). css ;
const ugly = '.container{display:flex;flex-direction:row;}.item{color:red;margin:0}' ;
const pretty = beautifyCss ( ugly , {
indent_size: 2 ,
selector_separator_newline: true ,
});
console . log ( pretty );
// .container {
// display: flex;
// flex-direction: row;
// }
//
// .item {
// color: red;
// margin: 0
// }
The CSS beautifier is simpler in scope than the JavaScript beautifier and has fewer options. For HTML and JavaScript inside CSS (e.g., in <style> blocks), use the HTML beautifier with embedded language support.
Language-specific overrides
When loading from .jsbeautifyrc, you can scope CSS settings under the css key:
{
"indent_size" : 4 ,
"css" : {
"indent_size" : 2 ,
"newline_between_rules" : true
}
}