0

Wondering how to update style sheet.

This works everywhere I was able to test, but not sure, if it is best solution:

runDemo();

var css = document.getElementsByTagName("style")[0];
getRule(css.sheet.rules, "div").
    style.width = 80 / [4, 5, 7][parseInt(Math.random() * 3)] + "%";

function getRule(rules, selector) {
    for (var i in rules) {
        if (rules[i].selectorText == selector)
            return rules[i];
    }
    return null;
}

function runDemo() {
    for (var i = Math.random() * 10 + 5; i > 0; i--) {
        var d = document.createElement("div");
        d.innerText = parseInt(i + 1);
        document.body.appendChild(d);
    }
}
body {
    display: flex;
    flex-flow: row wrap;
}

div {
    margin: 10px;
    padding: 3;
    text-align: center;
    border: 1px solid blue;
}
Jan
  • 2,178
  • 3
  • 14
  • 26

1 Answers1

0

I do not recommend editing the style rules this way. Is better tô add or remove the entire stylesheet. This way Will be far easyer to menage your styles.

You can fins how to do It here: Add stylesheet to Head using javascript in body

Michael Wallace
  • 402
  • 3
  • 9
  • Often you need to compute something depending on sources you have later in JS. Just found solution here https://stackoverflow.com/questions/28930846/how-to-use-cssstylesheet-insertrule-properly#28930990 – Jan Oct 04 '19 at 12:40
  • I do not ser too many reasons to add dynamic calculed css. In almost all cases os better tô haver a css for every display you will need and dynamic change the tags classes, not the CSS itself. But If you have a case where you realy need to do dynamic css, do just for these strict cases. All the rest of the time prefer to just change the classes from your tags or change the stylesheets for bigger changes of styles. – Michael Wallace Oct 04 '19 at 12:49
  • In case you need to show data of unknown size or shape, you need to compute some magic number(s) sometime - user-data driven SPA is sometimes hard to manage using fixed styles. – Jan Oct 04 '19 at 13:10
  • True. But you're using css flex layout. With flex you do not realy need fixed numbers. The layout can automatically adapt to the contents. Here is a good article about this: https://css-tricks.com/snippets/css/a-guide-to-flexbox/ Media queries will help you too: https://www.w3schools.com/Css/css3_mediaqueries_ex.asp – Michael Wallace Oct 06 '19 at 11:59