The why?!
Nowadays advanced frameworks like React, Vue, Angular, etc. are using CSS in JS syntax. You should write your own CSS in JS minimal engine to understand what's going on under the hood.
Javascript
function o2s(o, className) {
var elm = new Option();
Object.keys(o).forEach(function() {
(elm.style)[a] = o[a];
});
return `.${className}{\n${elm.getAttribute("style")}\n}`;
}
/**
* Class responsible for small css functionalities rendered in HTML like menu
*
* @export
* @class CSSMiniEngine
*/
export class CSSMiniEngine {
classes = [];
/**
* add css class with css params
*
* @memberof CSSMiniEngine
* @param {Partial<CSSStyleDeclaration>} o
* @param {string} className
*/
addClass = (o, className) => {
this.classes.push(o2s(o, className));
};
/**
* compile to style tag in head
*
* @memberof CSSMiniEngine
*/
compile = () => {
const head = document.head || document.getElementsByTagName("head")[0];
const style = document.createElement("style");
head.appendChild(style);
style.type = "text/css";
style.appendChild(document.createTextNode(this.classes.join("\n")));
};
}
Typescript
function o2s(o: Partial<CSSStyleDeclaration>, className: string) {
var elm = new Option();
Object.keys(o).forEach(function(a: string) {
(elm.style as any)[a as any] = o[a as any];
});
return `.${className}{\n${elm.getAttribute("style")}\n}`;
}
/**
* Class responsible for small css functionalities rendered in HTML like menu
*
* @export
* @class CSSMiniEngine
*/
export class CSSMiniEngine {
classes: string[] = [];
/**
* add css class with css params
*
* @memberof CSSMiniEngine
* @param {Partial<CSSStyleDeclaration>} o
* @param {string} className
*/
addClass = (o: Partial<CSSStyleDeclaration>, className: string) => {
this.classes.push(o2s(o, className));
};
/**
* compile to style tag in head
*
* @memberof CSSMiniEngine
*/
compile = () => {
const head = document.head || document.getElementsByTagName("head")[0];
const style = document.createElement("style");
head.appendChild(style);
style.type = "text/css";
style.appendChild(document.createTextNode(this.classes.join("\n")));
};
}
Usage example
Instantiate
const cssEngine = new CssMiniEngine()
Create Class
const className = "MyClass"
cssMiniEngine.addClass(
{
visibility: "visible",
position: "fixed",
background: "transparent",
border: "0",
textAlign: "center",
},
className
);
Use it
In pure js
const div = document.createElement("div")
div.classList.add(className)
In React
export const MyDiv = () => (
<div className={className}>Hello</div>
)
In the end call
cssEngine.compile()
So it will insert all your classes to DOM as a style tag
Thank you for reading!
Top comments (0)