MDN wants to learn about developers like you:

현재 번역은 완벽하지 않습니다. 한국어로 문서 번역에 동참해주세요.

CSSStyleSheet.insertRule() 메서드는 새 CSS 규칙을 현재 스타일 시트에 삽입합니다. (with some restrictions)

More specifically, though insertRule() is exclusively a method of the CSSStyleSheet, it actually inserts the rule into CSSStyleSheet.cssRulesthe CSSRuleList therein.

What the rule must contain depends on its type: For rule-sets the rule specifies both the selector and the style declaration. For at-rules, the rule specifies both the at-identifier and the rule content.


stylesheet.insertRule(rule, index)


  • rule is a DOMString containing the rule to be inserted,
    ...where rule specifies selector and declaration, or at-identifier and rule content.
  • index is an unsigned int representing the position in CSSStyleSheet.cssRules to insert at,
    ...where index-0 is first rule, and index-max is just after last rule and is the same as length of CSSStyleSheet.cssRules.

Note: index is now formally required, and omitting it may cause a warning or error. For example:

  • Chrome: " [Warning-icon]  Calling CSSStyleSheet.insertRule() with one argument is deprecated. Please pass the index argument as well"

반환 값

스타일 시트 규칙 목록내에 새로 삽입된 규칙의 인덱스.

제약 사항

CSS stylesheet rule-lists have a number of intuitive and not-so-intuitive restrictions affecting how and where rules can be inserted. Violating these will likely cause an error raised as a DOMException 

  • If index > number of rules in the stylesheet (the CSSRuleList.length), then aborts with IndexSizeError.
  • If rule cannot be inserted at index 0 due to some CSS constraint, then aborts with HierarchyRequestError.
  • If more than one rule is given in the rule parameter, then aborts with SyntaxError
  • If trying to insert an @import at-rule after a style rule, then aborts with HierarchyRequestError.
  • If rule is @namespace at-rule and list has more than just @import at-rules and/or @namespace at-rules, then aborts with InvalidStateError.


예제 1

// myStyle의 cssRules배열의 첫번째 인덱스에 새 규칙을 넣는다
myStyle.insertRule("#blanc { color: white }", 0); 

예제 2

 * Add a stylesheet rule to the document (may be better practice, however,
 * to dynamically change classes, so style information can be kept in
 * genuine stylesheets (and avoid adding extra elements to the DOM))
 * Note that an array is needed for declarations and rules since ECMAScript does
 * not afford a predictable object iteration order and since CSS is 
 * order-dependent (i.e., it is cascading); those without need of
 * cascading rules could build a more accessor-friendly object-based API.
 * @param {Array} rules Accepts an array of JSON-encoded declarations
 * @example
  ['h2', // Also accepts a second argument as an array of arrays instead
    ['color', 'red'],
    ['background-color', 'green', true] // 'true' for !important rules 
    ['background-color', 'yellow']
function addStylesheetRules (rules) {
  var styleEl = document.createElement('style'),

  // head에 스타일 엘리먼트(styleEl) 추가

  // Grab style sheet
  styleSheet = styleEl.sheet;

  for (var i = 0, rl = rules.length; i < rl; i++) {
    var j = 1, rule = rules[i], selector = rules[i][0], propStr = '';
    // If the second argument of a rule is an array of arrays, correct our variables.
    if ([1][0]) === '[object Array]') {
      rule = rule[1];
      j = 0;

    for (var pl = rule.length; j < pl; j++) {
      var prop = rule[j];
      propStr += prop[0] + ':' + prop[1] + (prop[2] ? ' !important' : '') + ';\n';

    // CSS 규칙 삽입
    styleSheet.insertRule(selector + '{' + propStr + '}', styleSheet.cssRules.length);


명세 상태 설명
CSS Object Model (CSSOM)
The definition of 'CSSStyleSheet.insertRule' in that specification.
Working Draft No change from Document Object Model (DOM) Level 2 Style Specification.
Document Object Model (DOM) Level 2 Style Specification
The definition of 'CSSStyleSheet.insertRule' in that specification.
Recommendation Initial definition

브라우저 호환성

Feature Chrome Edge Firefox (Gecko) Internet Explorer Opera Safari
Basic support (Yes) (Yes) (Yes) 9 (Yes) (Yes)
Feature Android Chrome for Android Edge Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support (Yes) (Yes) (Yes) (Yes) (Yes) (Yes) (Yes)

레거시 브라우저 지원

  • Internet Explorer - pre v9

    addRule(selector, rule [, index]);  --  Example: addRule('pre', 'font: 14px verdana'); // add rule at end

    Also note the non-standard removeRule() and .rules instead of deleteRule() and .cssRules respectively.

관련 참고

문서 태그 및 공헌자

 이 페이지의 공헌자: dotorify
 최종 변경: dotorify,