You don't need a css class on every html tag

Just a simple tip, if you’re just starting out with css. I see a lot of html developers adding ids or class names on every html tag they want to target in their stylesheet. This is really not necessary. You can combine tags in your css rules.

Simple example: suppose you want to style your input tags based on the page their are displayed on. You could create the following html pages. Page 1:

<body class="page1">
  <input .... />
</body>

Page 2:

<body class="page2">
  <input .... />
</body>

To change to styling of the input tag based on the page you can put the following css rules in your stylesheet:

body.page1 input { width: 25%; }
body.page2 input { width: 50%; }
CSS browser detection

I also use this to target different browsers. In javascript you can use object detection to determine what’s possible and what’s not. Unfortunately you can’t do this in css. Instead, i’m using a but of javascript to determine the browser, and add this information as a class to the body tag. Now it’s very easy to target different browsers in one css stylesheet.

For example, the following html would be the result of opening page 1 from the example above in internet explorer 7:

<body class="page1 msie msie7">
  <input .... />
</body>

I use jQuery to detect the browser, the relevant lines:

if ($.browser.msie) {
    bc = "msie";
    bc += " msie" + ($.browser.version).split(/./)[0];
}
$("body").addClass(bc);

Now i can have the following css rules to target different browsers:

  .msie.page1 input { width: 300px; }   /* internet explorer */
  .msie7.page1 input { width: 250px; }  /* internet explorer 7 */
  .page1 input { width: 400px; }        /* all other browsers */

I haven’t actually tested if internet explorer supports multiple classes in one css selector as used in this example, but it works in firefox.

blog comments powered by Disqus