CSS have rules like @media, @keyframes, etc. Can such be made using javascript, e.g. @myCustomRule. If yes then how ? If no then is there any alternative to that or just to go with CSS ?
-
2What are you trying to achieve?Turnip– Turnip2019-10-21 14:43:35 +00:00Commented Oct 21, 2019 at 14:43
-
3Those are called "at-rules". No, you cannot make custom at-rules in JS. developer.mozilla.org/en-US/docs/Web/CSS/At-ruleuser47589– user475892019-10-21 14:43:51 +00:00Commented Oct 21, 2019 at 14:43
-
You'd have to make your own pre-processor/pre-processing function that parses your stylesheet for your custom rule at compile time. The easiest way would be to create a webpack loader, or a function for whatever task runner you're using (if you're using one). When parsing, you'd have to replace your custom rule with native CSS that the browser can read.Jay Kariesch– Jay Kariesch2019-10-21 14:50:40 +00:00Commented Oct 21, 2019 at 14:50
-
Thats a great ideadebarchito– debarchito2019-10-21 16:09:49 +00:00Commented Oct 21, 2019 at 16:09
Add a comment
|
2 Answers
While you can't create your own custom @rules, you can use the CSSOM to create supported rules and insert them into one of the browser's stylehseets with JavaScript:
button.addEventListener('click', function () {
const sheets = document.styleSheets;
const lastStyleSheet = sheets[sheets.length - 1];
const rule = `@keyframes rotate {
0% {
transform: rotate(0deg);
} 100% {
transform: rotate(360deg);
}
}`;
lastStyleSheet.insertRule(rule, lastStyleSheet.rules.length);
box.classList.add('rotate');
});
#box {
border: 1px solid black;
height: 50px;
width: 50px;
}
#box.rotate {
animation: rotate 100ms infinite;
}
<div id="box"></div>
<button id="button">Add Animation via JS</button>
Comments
It turned out that there is a way, well explained here:
Defining Custom At-Rules in CSS
it uses jsincss and jsincss-element-query