Skip to content
Advertisement

Can javascript make a custom @rule of css?

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 ?

Advertisement

Answer

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>
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement