18.5. Dynamically Creating Browser-Specific Stylesheets

Problem

You need to vary the look and feel of your application pages depending on the platform (Mac or Windows) that is being used.

Solution

Place an asp:Literal control in the head section of the .aspx file, and then set the text property of the control to an HTML style element created programmatically in the code-behind. Use the properties of the Request.Browser object to determine the platform type and control the generation of the style element.

In the .aspx file, place an asp:Literal control in the head section.

In the code-behind class for the page, use the .NET language of your choice to:

  1. Use the Platform property of the Request.Browser object to obtain the browser’s platform.

  2. Check the platform string for the presence of the substring, such as “mac”, which indicates whether the browser is running on a Mac platform.

  3. Based on the platform, programmatically create the HTML style element.

  4. Set the Text property of the asp:Literal control in the head section of the .aspx file to the created HTML style elements.

The .aspx file used for this example is shown in Example 18-13. The code-behind is shown in Example 18-14 (VB) and Example 18-15 (C#).

Discussion

HTML is not always rendered the same. Different browsers and different platforms render the HTML in a variety of ways. This sometimes requires using a different stylesheet as a function of the browser or platform the browser is running on (Windows, Mac, etc.) to get the same visual ...

Get ASP.NET Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.