Changing a CSS style dynamically

February 10th, 2004

Because of the annoyingly different way that IE and Mozilla handle margins and padding, I needed to modify a style for an h2 heading in IE only – adding a little padding at the top to move the heading down slightly in IE. In Mozilla it looked OK, so I wanted to detect the browser and if it was IE, change the stylesheet.

The page was a one-off, so I didn't want to go down the route of having 2 external stylesheet files, I wanted to keep everything in the page itself.

The solution I used owes something to the information on www.quirksmode.org/dom/changess.html, which explains how to reference a rule within a stylesheet from a JavaScript statement.

So, I have a stylesheet beginning:

<style type="text/css">
  /****Leave this h2 rule as the first rule in this stylesheet
       as it's referenced as such (i.e. rules[0] in the JavaScript below)***/
  h2 {
    font-family: Verdana, Arial, Helvetica, sans-serif;
    font-size: 18px; font-weight: bold;
    margin-top: 0px
  }
  ...

and then, after the stylesheet, the following JavaScript:

<script language="JavaScript">
  <!--
  browserName=navigator.appName;
  if (browserName=="Microsoft Internet Explorer") {
    document.styleSheets[0].rules[0].style.marginTop = '18px';  
  }
  //-->
</script>

This has no effect in browsers other than IE. In IE the first rule in the first stylesheet on the page (styleSheets[0].rules[0]) gets modified, changing the marginTop style to 18 pixels.

Leave a comment