5

Possible Duplicate:
Embedding extra styles with noscript
Define css if javascript is not enabled

I am trying to define specific CSS styles only if Javascript is turned off. I am using:

<noscript>
    <style type="text/css">
    .needjs {display:none !important;}
    .mwnojs { margin-top: 40px !important; }
    </style>
</noscript>

When trying to validate the page source, I get the error "Element style not allowed as child of element noscript in this context".

So, how would I go about doing this while keeping my markup valid?

Community
  • 1
  • 1
MultiDev
  • 9,449
  • 22
  • 69
  • 132
  • 2
    Yuck. Don't use `!important`. – gilly3 Dec 19 '12 at 21:51
  • 1
    modernizer - http://modernizr.com/ – jsweazy Dec 19 '12 at 21:51
  • What's wrong with `!important`? – MultiDev Dec 19 '12 at 21:53
  • 1
    None of the accepted answers to the "duplicates" address the html validation error. But, [this (not accepted) answer](http://stackoverflow.com/a/1332058/361684) *is* correct. Move your ` – gilly3 Dec 19 '12 at 22:01
  • [@stefsull sums it up nicely](https://twitter.com/stefsull/status/70631020352913408): "Using `!important` in your CSS usually means you're narcissistic & selfish or lazy. Respect the devs to come..." [More here](http://james.padolsey.com/usability/dont-use-important/) – gilly3 Dec 19 '12 at 22:07

5 Answers5

3

<noscript> tags are "body" tags and <style> tags are "head" tags. Therefor you get an error.

You should make non-javascript style default and then use js to change your style. See here for more details: https://stackoverflow.com/a/218917/1068167

Community
  • 1
  • 1
span
  • 5,144
  • 5
  • 47
  • 96
1

Seems very similar to this question

"To clear up the validation issue: noscript is only allowed in the body element, style only allowed in the head. Therefore, the latter is not allowed within the former."

It might matter where your <noscript> tag is located.

Community
  • 1
  • 1
Jon Harding
  • 4,782
  • 12
  • 46
  • 88
0

Try something like this:

<html class="nojs">
<head>
<script type="text/javascript">
document.getElementByTagName("html")[0].className="";
</script>
<style>
html#nojs {
   /* do something */
}
</style>

This removes a class while loading the page. If javascript is not activated the class won't be removed.

rekire
  • 45,039
  • 29
  • 149
  • 249
0

You can get around this by having those classes in your default stylesheet and have JavaScript get rid of them when the page loads. This will only work if JavaScript is enabled otherwise it would load the desired styles.

ama2
  • 2,511
  • 2
  • 17
  • 28
0

You could for example do it the other way around and disable some css file via javascript which doesn' t happen if it's not activated.

Ace7k3
  • 364
  • 2
  • 9