JS Summary of Ways to Set CSS Styles

  • 2021-07-13 03:59:28
  • OfStack

1. Set the properties of style directly. Use this setting in some cases! Invalid important value

If the attribute has a '-' sign, write it in the form of a hump (e.g. textAlign). If you want to keep the-sign, write it in the form of brackets element. style ['text-align'] = '100px';


element.style.height = '100px';

2. Set properties directly (only for some properties, related styles will be automatically recognized)


element.setAttribute('height', 100);
element.setAttribute('height', '100px');

3. Set the properties of style


element.setAttribute('style', 'height: 100px !important');

! The css definition of important is to have the highest priority.

4. Use setProperty if you want to set! important, this is the recommended way to set the third parameter


element.style.setProperty('height', '300px', 'important');

5. Change class, such as JQ, and change class related methods


element.className = 'blue';
element.className += 'blue fb';

6. Set cssText


element.style.cssText = 'height: 100px !important';
element.style.cssText += 'height: 100px !important';

7. Create and introduce a new css style file


function addNewStyle(newStyle) {
      var styleElement = document.getElementById('styles_js');
      if (!styleElement) {
        styleElement = document.createElement('style');
        styleElement.type = 'text/css';
        styleElement.id = 'styles_js';
        document.getElementsByTagName('head')[0].appendChild(styleElement);
      }
      styleElement.appendChild(document.createTextNode(newStyle));
    }
    addNewStyle('.box {height: 100px !important;}');

8. Use addRule, insertRule


//  Operate in the original style 
    document.styleSheets[0].addRule('.box', 'height: 100px');
    document.styleSheets[0].insertRule('.box {height: 100px}', 0);
    //  Or insert a new style 
    var styleEl = document.createElement('style'),
      styleSheet = styleEl.sheet;
    styleSheet.addRule('.box', 'height: 100px');
    styleSheet.insertRule('.box {height: 100px}', 0);
    document.head.appendChild(styleEl);   

Related articles: