What is css-tree?
The css-tree npm package is a tool for parsing and manipulating CSS. It allows users to parse CSS strings into an abstract syntax tree (AST), walk over nodes in the tree, generate CSS strings, and more. It is useful for tasks such as CSS minification, linting, and transformation.
What are css-tree's main functionalities?
Parsing CSS to AST
This feature allows you to parse a CSS string and convert it into an abstract syntax tree (AST) for further manipulation or analysis.
const csstree = require('css-tree');
const ast = csstree.parse('.example { color: red; }');
Walking the AST
This feature enables you to traverse the AST and apply functions or extract information from specific nodes.
csstree.walk(ast, function(node) {
if (node.type === 'ClassSelector') {
console.log(node.name);
}
});
Generating CSS from AST
After manipulating the AST, you can generate a CSS string from the modified AST, which can be used in stylesheets or injected into web pages.
const modifiedAST = csstree.parse('.example { color: blue; }');
const css = csstree.generate(modifiedAST);
Minifying CSS
css-tree can be used to minify CSS by parsing it with compression options and then translating the AST back to a CSS string.
const compressedCSS = csstree.translate(csstree.parse('.example { color: red; }', { compress: true }));
Other packages similar to css-tree
postcss
PostCSS is a tool for transforming CSS with JavaScript plugins. It can do similar tasks as css-tree, such as parsing, walking the AST, and generating CSS. PostCSS is plugin-based, which makes it more extensible and allows for a wide range of transformations.
sass
Sass is a preprocessor scripting language that is interpreted or compiled into CSS. It offers more syntactic features compared to css-tree, such as variables, nesting, and mixins, but it is not primarily focused on parsing and manipulating existing CSS.
less
Less is another CSS pre-processor, similar to Sass, that extends the capabilities of CSS with dynamic behavior such as variables, mixins, operations, and functions. Less and css-tree serve different purposes, with Less focusing on writing CSS in a more functional way and css-tree on parsing and manipulation.
clean-css
clean-css is a fast and efficient CSS optimizer for Node.js and the browser. It focuses on minification, which is one of the features of css-tree, but does not provide a general-purpose CSS parsing and manipulation API.

CSSTree

CSSTree is a tool set to work with CSS, including fast detailed parser (string->AST), walker (AST traversal), generator (AST->string) and lexer (validation and matching) based on knowledge of spec and browser implementations. The main goal is to be efficient and W3C spec compliant, with focus on CSS analyzing and source-to-source transforming tasks.
NOTE: The project is in alpha stage since some parts need further improvements, AST format and API are subjects to change. However it's stable enough and used by packages like CSSO (CSS minifier) and SVGO (SVG optimizer) in production.
Features
-
Detailed parsing with an adjustable level of detail
By default CSSTree parses CSS as detailed as possible, i.e. each single logical part is representing with its own AST node (see AST format for all possible node types). The parsing detail level can be changed through parser options, for example, you can disable parsing of selectors or declarations for component parts.
-
Tolerant to errors by design
Parser behaves as spec says: "When errors occur in CSS, the parser attempts to recover gracefully, throwing away only the minimum amount of content before returning to parsing as normal". The only thing the parser departs from the specification is that it doesn't throw away bad content, but wraps it in the special nodes, which allows processing it later.
-
Fast and efficient
CSSTree is created with focus on performance and effective memory consumption. Therefore it's one of the fastest CSS parsers at the moment.
-
Syntax validation
The build-in lexer can test CSS against syntaxes defined by W3C. CSSTree uses mdn/data as a basis for lexer's dictionaries and extends them with vendor specific and legacy syntaxes. Lexer can only check the declaration values currently, but this feature will be extended to other parts of the CSS in the future.
Docs
Tools
Related projects
Usage
Install with npm:
> npm install css-tree
Use in your code:
var csstree = require('css-tree');
var ast = csstree.parse('.example { world: "!" }');
csstree.walk(ast, function(node) {
if (node.type === 'ClassSelector' && node.name === 'example') {
node.name = 'hello';
}
});
console.log(csstree.generate(ast));
Top level API

License
MIT
1.0.0-alpha.27 (January 14, 2018)
- Generator
- Changed node's
generate()
methods invocation, methods now take a node as a single argument and context (i.e. this
) that have methods: chunk()
, node()
and children()
- Renamed
translate()
to generate()
and changed to take options
argument
- Removed
translateMarkup(ast, enter, leave)
method, use generate(ast, { decorator: (handlers) => { ... }})
instead
- Removed
translateWithSourceMap(ast)
, use generate(ast, { sourceMap: true })
instead
- Changed to support for children as an array
- Walker
- Changed
walk()
to take an options
argument instead of handler, with enter
, leave
, visit
and reverse
options (walk(ast, fn)
is still works and equivalent to walk(ast, { enter: fn })
)
- Removed
walkUp(ast, fn)
, use walk(ast, { leave: fn })
- Removed
walkRules(ast, fn)
, use walk(ast, { visit: 'Rule', enter: fn })
instead
- Removed
walkRulesRight(ast, fn)
, use walk(ast, { visit: 'Rule', reverse: true, enter: fn })
instead
- Removed
walkDeclarations(ast, fn)
, use walk(ast, { visit: 'Declaration', enter: fn })
instead
- Changed to support for children as array in most cases (
reverse: true
will fail on arrays since they have no forEachRight()
method)
- Misc
- List
- Added
List#forEach()
method
- Added
List#forEachRight()
method
- Added
List#filter()
method
- Changed
List#map()
method to return a List
instance instead of Array
- Added
List#push()
method, similar to List#appendData()
but returns nothing
- Added
List#pop()
method
- Added
List#unshift()
method, similar to List#prependData()
but returns nothing
- Added
List#shift()
method
- Added
List#prependList()
method
- Changed
List#insert()
, List#insertData()
, List#appendList()
and List#insertList()
methods to return a list that performed an operation
- Changed
keyword()
method
- Changed
name
field to include a vendor prefix
- Added
basename
field to contain a name without a vendor prefix
- Added
custom
field that contain a true
when keyword is a custom property reference
- Changed
property()
method
- Changed
name
field to include a vendor prefix
- Added
basename
field to contain a name without any prefixes, i.e. a hack and a vendor prefix
- Added
vendorPrefix()
method
- Added
isCustomProperty()
method