Another area where browser detection can improve your web pages is in helping you present a consistent page design across different browsers. As you probably already know from experience, different default font sizes, margins, and even color rendering can warp what is an attractive page in one browser into an unreadable mess in the next.
One of the most noticeable examples of how browsers render pages differently is in the variety of default font sizes among different versions of Netscape Navigator and Internet Explorer. Form elements are another common culprit; they are rendered at wildly differing sizes and margins in the various browsers. Even the use of Cascading Style Sheets (CSS) doesn't solve these problems, because different browsers apply styles in slightly different ways. Combined, these differences force designers to continually test all target browsers to create pages that look decent across all platforms.
detection code with style sheets that are targeted at different browsers, we can produce consistent
pages across all browsers. First, let's take a look at the problem we are trying to solve. Example
6-8 shows a simple form that uses a single style sheet,
<html> <head> <title>A Form</title> <link rel="stylesheet" href="styles.css" type="text/css"> </head> <body> <form name="form1" method="post" action=""> <table border="0" width="100%" cellpadding="3"> <tr> <th bgcolor="#00FF00"> <span>Please Fill Out the Following Form:</span> </th> </tr> <tr> <td> <input type="text" name="textfield" value="Enter Keywords Here" size="20"> <select name="select"> <option>Default Selection</option> <option selected>Selection 2</option> <option>Selection 3</option> </select> <input type="submit" name="Submit" value="Submit"> </td> </tr> <tr> <td> <p>Shall we place you on our mailing list?</p> <input type="radio" name="radiobutton" value="radiobutton"> Yes<br> <input type="radio" name="radiobutton" value="radiobutton">No </td> </tr> <tr> <td> <input type="checkbox" name="checkbox" value="checkbox">Remember Me</td> </tr> </table> </form> </body> </html>
Example 6-8: A simple form that uses a single style sheet
Notice the use of the link tag to link the styles.css style sheet into the HTML document. Figure 6-2 shows how different this form appears in Navigator 4 and IE 5.5, despite the use of a single style sheet.
Figure 6-2: A simple form displayed in Navigator 4 and IE 5.5
Example 6-9: Using browser detection to apply the appropriate style sheet
If the browser is Navigator 4, the script links in nn4.css; with IE 5.5, the style sheet is ie55.css. For simplicity, this example detects just two browsers, but you can see how it could be extended to handle others. Figure 6-3 shows how much more consistent our form looks in Navigator 4 and IE 5.5 with the browser-specific styles applied.
Figure 6-3: A form using browser-specific style sheets, displayed in Navigator 4 and IE 5.5
Created: December 17, 2001
Revised: December 17, 2001