6

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 ?

4
  • 2
    What are you trying to achieve? Commented Oct 21, 2019 at 14:43
  • 3
    Those are called "at-rules". No, you cannot make custom at-rules in JS. developer.mozilla.org/en-US/docs/Web/CSS/At-rule Commented 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. Commented Oct 21, 2019 at 14:50
  • Thats a great idea Commented Oct 21, 2019 at 16:09

2 Answers 2

6

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>

Sign up to request clarification or add additional context in comments.

Comments

3

It turned out that there is a way, well explained here:

Defining Custom At-Rules in CSS

it uses jsincss and jsincss-element-query

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.