Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Is it possible to create full media query rules on the fly using Javascript or jQuery?

I've used numerous media queries to target generalised viewports and specific devices/screens using inline CSS, imports and linked files:

@media screen and (min-width:400px) { ... }
@import url(foo.css) (min-width:400px);
<link rel="stylesheet" type="text/css" media="screen and (min-width: 400px)" href="foo.css" />

I can add/remove classes using jQuery:

$("foobar").click(function(){
  $("h1,h2,h3").addClass("blue");
  $("div").addClass("important");
  $('#snafu').removeClass('highlight');
});

I've also look at document.stylesheets and the seemingly archaic and browser-specific:

  document.styleSheets[0].insertRule("p{font-size: 20px;}", 0)

But I can't find any reference to programatically generating:

  @media screen and (min-width:400px)

from javascript directly or in any form.

share|improve this question
1  
Just updating an existing style element's contents seems to work fine: jsfiddle.net/vfLS3 – Explosion Pills Apr 17 at 3:35
Do you mean adding a css media query rule? – itsstephyoutrick Apr 17 at 3:39
@ExplosionPills That is perfect and a worthy 'answer' – nickhar Apr 17 at 3:46
add comment (requires an account with 50 reputation)

1 Answer

up vote 4 down vote accepted

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/

share|improve this answer
add comment (requires an account with 50 reputation)

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.