Generating CSS media queries with javascript or jQuery

You can just update an existing <style> element (or create one) textContent to contain the rule, which will make it effective in the given context.

document.querySelector('style').textContent +=
    "@media screen and (min-width:400px) { div { color: red; }}"

http://jsfiddle.net/vfLS3/


For general purpose use, you can append a style sheet to document.head. Then you can put any mods in there you want -- including media queries. Since it's the final style sheet in document.head, it overrides any prior CSS rules.

Vanilla JavaScript:

    let style = document.getElementById('custom-styles');
    if (!style) {
      style = document.createElement('style');
      style.id = "custom-styles";
      document.head.appendChild(style);
    }
    style.innerHTML =
      "@media screen and (min-width:400px) {...}";

I use this way. This allows to update multiply styles in document

in HTML:

<style class="background_image_styles">
</style>

in JS

$(".background_image_styles").text("@media (min-width: 1200px) {.user_background_image{background-image: url('https://placehold.it/1200x300');}}");