最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Shortest way to add CSS rules with vanilla JS - Stack Overflow

programmeradmin1浏览0评论

I'm working on a library that I'm trying to keep it below 1KB. Which I'm already very close to my limits. I need to add a css rule to control show hide behaviour.

[hidden]{ display:none !important }

HTML page does not have any style tags. This will be only rule I need. I can only add it with pure JS. I do not want to change the style of an element with el.style.display = 'none'. I want to do it with an attribute.

So how can I add this, I found solutions that create a style element and set it's innerHTML and append it to head element. I'm hoping I can get an answer / a hack to maybe do it with less characters.

I'm working on a library that I'm trying to keep it below 1KB. Which I'm already very close to my limits. I need to add a css rule to control show hide behaviour.

[hidden]{ display:none !important }

HTML page does not have any style tags. This will be only rule I need. I can only add it with pure JS. I do not want to change the style of an element with el.style.display = 'none'. I want to do it with an attribute.

So how can I add this, I found solutions that create a style element and set it's innerHTML and append it to head element. I'm hoping I can get an answer / a hack to maybe do it with less characters.

Share Improve this question asked Jun 30, 2019 at 12:31 chickenschickens 22.4k7 gold badges61 silver badges57 bronze badges 1
  • Create your stylesheet inside JS file then create script tag. InnerText the stylesheet and append child to head – Sergey Commented Jun 30, 2019 at 13:11
Add a ment  | 

2 Answers 2

Reset to default 5

This is the shortest I got, please make it shorter if you can.

const addCSS = s => document.head.appendChild(document.createElement("style")).innerHTML = s;

// Usage:
addCSS("[hidden]{ display:none !important }");

If you want to hide an element with an attribute, simply use the attribute hidden.

Example:

<div hidden class="container"></div>

If you do not want to use el.style.display = 'none', you could also use cssText to use your whole style in only 1 string.

Example:

document.querySelector('.container').style.cssText = 'width: 100vw; height: 100vh; background: rebeccapurple;';
<div class="container"></div>

Another option would be using the method CSSStyleSheet.insertRule().

The CSSStyleSheet.insertRule() method inserts a new CSS rule into the current style sheet, with some restrictions.

Example:

const css = window.document.styleSheets[0];
css.insertRule(`
  .container {
    width: 100vw;
    height: 100vh;
    background: rebeccapurple;
  }
`, css.cssRules.length);
<div class="container"></div>

发布评论

评论列表(0)

  1. 暂无评论