CSSX is not a new language. It's still the CSS that we know and use every day. The difference is that we write it inside a JavaScript context. That's possible because we now have an access to CSSX transpiler. It understand and successfully transforms expressions like this:
sheet.add(<style>
body {
margin: 0;
padding: 0;
}
</style>);
The <style>
tag returns a plain JavaScript object which we use together with CSSX stylesheet to manage our styles. For example, to append a new CSS rule for all paragraphs on our page we can use the following:
sheet.add(<style>
p {
font-size: 1em;
line-height: 1.2em;
}
</style>);
It returns an object.
Example:
var sheet = cssx('id');
sheet.add(<style>
body {
margin: 0;
padding: 0;
}
</style>);
Same as:
var sheet = cssx('id');
sheet.add({
body: {
margin: 0,
padding: 0
}
});
The id
passed to cssx
is optional. If you don't provide one the library will generate it for you. However, we should say that running only cssx()
generates a new stylesheet every time. So if we plan to execute such code many times it's good to provide an ID.
It returns a vanilla JavaScript object literal.
Example:
var styles = <style>{
font-size: 1em;
line-height: 1.2em;
}</style>;
Same as :
var styles = {
"font-size": "1em",
"line-height": "1.2em"
};
We are writing CSSX in JavaScript context. So it has an access to all the data in the current scope.
var property = 'size';
var value = 18;
var sheet = cssx();
sheet.add(<style>
body {
font-{{ property }}: {{ value + 2 }}px;
}
</style>);
There are three ways to define dynamic expressions:
- ` ... ` (grave accents (backticks))
{{ ... }}
<% ... %>
The transpiler converts the string inside the expression to a valid JavaScript. The code above is transformed to the following:
var property = 'size';
var value = 18;
var sheet = cssx();
sheet.add((function () {
var _2 = {},
_3 = {};
_3["font-" + property] = value + 2 + "px";
_2['body'] = _3;
return _2;
}.apply(this)));
And the produced CSS:
body {
font-size: 20px;
}
Check out the plugin docs to see how to use CSSX together with PostCSS.
Check out CSSX client-side library or learn how to use the transpiler.