Lesson 1: Using Cascading Style Sheets
Cascading style sheets (CSS) collect and organize all of the formatting information applied to HTML elements on a Web form. Because they keep this information in a single location, style sheets make it easy to adjust the appearance of Web applications.
Visual Studio .NET includes style-editing tools, along with a default style sheet that is created as part of new Web application projects. In this lesson, you ll learn how to use the Visual Studio .NET tools to modify the default style sheet, attach the sheet to Web forms, and switch between style sheets at run time.
After this lesson, you will be able to
Explain how Microsoft ASP.NET applies styles defined at different levels within a Web form
Attach a style sheet to a Web form
Modify styles within a style sheet
Create new styles and add them to a style sheet
Create style classes that can be applied to different types of HTML elements
Change style sheets at run time to provide an enlarged-type version of a Web form or to format a Web form for printing
Use behaviors to control dynamic elements on a Web form
Estimated lesson time: 35 minutes
How Styles Work
As mentioned in the opening of this lesson, style sheets store formatting in a single location: the CSS file. However, formatting can be applied at three different levels within a Web application. Before you start working with style sheets, you should understand how styles defined at different levels affect formatting. Table 13-1 describes these levels and how they apply to the elements on a Web form.
Level | Defined in | Applies to |
Global | The style sheet file | All pages referencing the style sheet |
Page | The page s head element | All elements on the current page |
Inline | The HTML element itself | Only the current element |
These three levels follow precedence rules that are similar to the levels of scoping you re already familiar with as a programmer. Inline formatting takes precedence over local formatting, which, in turn, takes precedence over global formatting. These precedence rules are the reason style sheets are referred to as cascading. Figure 13-1 illustrates how styles defined at different levels are applied to a paragraph element.
Figure 13-1. Style precedence
The following HTML shows the style definitions used to create the output shown in Figure 13-1:
<HTML> <HEAD> <title>WebForm1</title> <!-- (1) Style sheet reference. --> <LINK REL="stylesheet" TYPE="text/css" HREF="Styles.css"> <!-- (2) Page-level style definition. --> <style> p { font-family: 'Comic Sans MS', Lucida Sans, sans-serif; font-size: medium; } </style> </HEAD> <body> <p>The alignment is from the style sheet.</p> <p>The font is from the style in the page's head element.</p> <!-- (3) Inline style definition --> <p style="FONT-SIZE: large; FONT-STYLE: italic">The italic is from the inline style.</p> </body> </HTML> <!-- (1) From Styles.css style sheet referenced in HEAD element. --> p { font-size: small; text-align: center; }
The preceding example shows how style attributes can be applied to a single element at different levels. The font-size attribute is applied at all three levels, but you see only the effects of the page level and inline settings because the page setting takes precedence over the style sheet setting. The text-align, font-family, and font-style attributes are each defined only once, so their effects are additive.
There are a couple of advantages to storing style definitions in a style sheet file (.css) rather than locally in each Web form or inline with each HTML element:
Formatting can be maintained in one location so that you make changes only once for an entire application.
Several sets of parallel formatting rules can be maintained in separate style sheets for formatting output on different devices or for different user needs. For example, an application might provide standard, enlarged-type, and printer-friendly style sheets that the user can select at run time.
TIP
In general, you should use page and inline styles only when you have a really good reason to override the global styles. Relying heavily on page and inline styles can make it difficult to maintain the formatting in a Web application.
Using Style Sheets with Web Forms
When you create a new Visual Basic .NET Web application, Visual Studio .NET automatically creates a style sheet named Styles.css for the application. However, Visual Studio .NET does not automatically use that style sheet in any of the Web forms or HTML pages you create.
To use that style sheet, you must add a link element to the page s head element, as shown here in boldface:
<HEAD> <title>WebForm1</title> <meta name="GENERATOR" content="Microsoft Visual Studio.NET 7.0"> <meta name="CODE_LANGUAGE" content="Visual Basic 7.0"> <meta name="vs_defaultClientScript" content="JavaScript"> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5"> <LINK REL="stylesheet" TYPE="text/css" HREF="Styles.css"></HEAD>
IMPORTANT
Only Microsoft Visual Basic .NET projects are created with a new default style sheet. For Microsoft Visual C# projects, you must create a new style sheet from scratch or cut and paste the contents of a default style sheet from a Visual Basic .NET project to get started.
Modifying Styles
Use the Style Builder to change the appearance of any of the styles in a style sheet. Changes to the style sheet change the appearance of all Web forms that reference that style sheet.
To modify a style, follow these steps:
Open the style sheet in Visual Studio. Visual Studio .NET displays the style definitions in the Document window and an outline of the style sheet in the Tool window, as shown in Figure 13-2.
Figure 13-2. Style sheet Document and Tool windows
Select the style to modify from the Tool window. Visual Studio .NET displays the definition for that style in the Document window.
Right-click in the style definition or right-click the style in the Tool window, and select Build Style from the shortcut menu. Visual Studio .NET displays the Style Builder Wizard, as shown in Figure 13-3.
Figure 13-3. Style Builder
Use the Style Builder to compose the formatting that you want to add or modify in the selected style, and then click OK.
When you have finished, you ll see that the Style Builder adds the new or modified style attributes to the style definition.
Adding Styles
So far, we have created applied styles using HTML element names. CSS uses the element name to locate the default formatting to apply to each element. However, you can also apply styles using class names or element IDs.
Using class names allows you to apply a single style to a number of different elements or to style the same element differently, depending on how the element is used. Using element IDs allows you to apply a style to a unique element on one or more Web forms.
To add a style, follow these steps:
Open the style sheet. Right-click the style sheet s Document or Tool window, and select Add Style Rule from the shortcut menu. Visual Studio .NET displays the Add Style Rule Wizard, as shown in Figure 13-4.
Figure 13-4. Add a style
Select the type of style you want to create. You can create styles that apply to HTML elements, classes, or specific element IDs. Type the name of the item to create the style for and click the > (Add) button to add the item to the style rule.
Repeat step 2 for each item you want the style to apply to.
Using Style Classes
Style classes allow you to apply the same formatting to different HTML elements on a Web form. When you create a style rule for a class, Visual Studio .NET adds a style definition to the style sheet using a .classname identifier, as shown here:
.emphasis { font-style: italic; }
The preceding .emphasis style class formats all elements that use the class in italic, as shown in Figure 13-5.
Figure 13-5. Applying a style class
You apply the style class to HTML elements by using the class attribute. You apply the style to server controls by using the CssClass attribute. The following HTML shows this difference in boldface:
<p>This is a paragraph containing <span >emphasis</span>.</p> <asp:TextBox Runat="server" Css>Some text </asp:TextBox>
Creating Styles for Specific Elements
You can also create styles for specific elements on a Web form based on their element IDs. Element IDs must be unique for each element on a page, so formatting set by element ID can apply to only one element on each page. When you create a style rule for an element ID, Visual Studio .NET adds a style definition to the style sheet using a #elementID identifier, as shown here:
#inserted { text-decoration: underline; } #deleted { text-decoration: line-through; }
The preceding style definitions format elements with the ID inserted as underlined text and elements with the ID deleted with strikethrough, as shown in Figure 13-6.
Figure 13-6. Applying a style by element ID
Styles applied in Visual Studio .NET don t always show up right away in the Web Forms Designer. If you re not seeing the formatting applied through a particular style, try the following:
Make sure the style sheet has been saved.
Switch the Web form between HTML view and the Design view.
Right-click the Web form, and select View In Browser from the shortcut menu.
Creating Nested Styles
If you look at the style definitions in the default style sheet, Styles.css, you ll notice that some style definitions list multiple element names. These definitions establish which formatting to use for nested elements. For example, the following styles specify different bullet types for nested, unnumbered lists:
UL LI { list-style-type: square ; } UL LI LI { list-style-type: disc; } UL LI LI LI { list-style-type: circle; }
The preceding nested files format the nested list items, as shown in Figure 13-7.
Figure 13-7. Nested list
To create your own nested styles, add multiple items to the Style rule hierarchy in the Add Style Rule dialog box, as shown in Figure 13-8.
Figure 13-8. Creating nested styles
Changing Style Sheets at Run Time
As mentioned, you can create multiple style sheets and then allow the user to select the styles to use at run time to format the Web form for printing or to provide features such as enlarged-type versions of Web forms.
To switch style sheets automatically when printing a Web form, use the media attribute of the style sheet link element to specify the style sheet to use for printing and screen display. For example, the following link elements apply formatting from the default style sheet when the Web form is displayed on screen, but they use the Print.css style sheet when the user prints the Web form:
<LINK REL="stylesheet" TYPE="text/css" HREF="Styles.css" media="screen"> <LINK REL="stylesheet" TYPE="text/css" HREF="Print.css" media="print">
To switch between style sheets at run time, create a client-side script to change the href element of the style sheet link element. For example, the following HTML creates a Web form that switches between the style sheets Styles.css and BigType.css when the user clicks a hyperlink in text:
VBScript
<HTML> <HEAD > <title>ChangeSheets</title> <LINK REL="stylesheet" TYPE="text/css" HREF="Styles.css"> <script language="vbscript"> ' VBScript ' Switch between default and large-type style sheets. Sub SwitchSheets() If document.all("ScreenStyle").GetAttribute("HREF") = "Styles.css" then document.all("ScreenStyle").SetAttribute "HREF", "BigType.css", 0 else document.all("ScreenStyle").SetAttribute "HREF", "Styles.css", 0 end if End Sub </script> </HEAD> <body> <form method="post" runat="server"> <h2>Changing Style Sheets at Run-Time</h2> <p>This page first appears using the default style sheet.</p> <p><a onclick="SwitchSheets" href="#">Click here </a> to switch between the standard and the enlarged-type version.</p> </form> </body> </HTML>
JScript
<HTML> <HEAD> <title>ChangeSheets</title> <LINK REL="stylesheet" TYPE="text/css" HREF="Styles.css" media="screen"> <LINK REL="stylesheet" TYPE="text/css" HREF="Print.css" media="print"> <script id=clientEventHandlersJS language=jscript> function SwitchSheets() { // Switch between default and large-type style sheets. if (document.all["ScreenStyle"].getAttribute("HREF") == "Styles.css") document.all["ScreenStyle"].setAttribute ("HREF", "BigType.css", 0); else document.all["ScreenStyle"].setAttribute ("HREF", "Styles.css", 0); } </script> </HEAD> <body MS_POSITIONING="FlowLayout"> <FORM method="post" runat="server"> <H2>Changing Style Sheets at Run-Time</H2> <P>This page first appears using the default style sheet.</P> <P><A onclick="SwitchSheets();" href="#">Click here</A> to switch between the standard and the enlarged-type version.</P> <A href="Behave.aspx">Next>></A> </FORM> </body> </HTML>
Figure 13-9 shows the how the Web form changes at run time when the user changes the style sheets by clicking the link.
Figure 13-9. Changing style sheets at run time
Using Behaviors
In addition to formatting, styles can also define behaviors that HTML elements exhibit at run time. Behaviors are a sort of dynamic formatting: because Web content isn t always static, style sheets use behaviors to describe dynamic changes.
For example, HTML+TIME animations use the time class to apply animations to HTML elements on a page, as shown here:
<style> .time {behavior: url(#default#time2);} </style>
The behavior property imports behavior files that contain Microsoft JScript or Microsoft Visual Basic Scripting Edition (VBScript) code that controls what the behavior does. The Behaviors Library topic in the Visual Studio .NET online Help provides a number of sample behaviors that you can download and use in your own code.
For example, the following HTML imports the Movable.htc sample behavior file and uses it to create a paragraph that the user can drag to a new location on the Web form at run time:
<HEAD> <title>Behave</title> <style> .movable {behavior: url(behaviors/movable.htc); CURSOR: move; mv--boundary: 0 800 600 0} </style> </HEAD> <body> <form method="post" runat="server"> <p >You can drag this text around the screen.</p> </form> </body> </HTML>
In the preceding HTML, the style definition for the movable class includes the URL of the behavior file, the cursor style to use, and the boundaries the elements are confined to. The style is applied by the p element s class attribute. At run time, the user can drag the paragraph around the screen, as shown in Figure 13-10.
Figure 13-10. The movable behavior
The movable behavior can be applied to any element on a Web form, including server controls. Some behaviors, however, can be applied only to certain types of controls. For instance, the ColorPick behavior shown in the following code can be applied only to HTML Text Field controls (input elements of type text):
<HTML xmlns:control> <HEAD> <title>Behave</title> <style> .color { BEHAVIOR: url(behaviors/ColorPick.htc) } </style> </HEAD> <body> <form method="post" runat="server"> <p>Use the color picker below to change the background color:</p> <input type="text" value="#fFFf00" onchange="document.bgColor=ColorPic.value;" style="cp--grid-size:2"> </form> </body> </HTML>
The preceding HTML displays a color palette that the user can click to change the background color at run time, as shown in Figure 13-11.
Figure 13-11. The ColorPick behavior
Finally, some behaviors create their own types of elements that you can use on a Web form. For example, the Slider sample behavior creates a slider element that you can use to get input from a user. To use the Slider control, you must first add an xmlns attribute to the Web form s html element to declare the name for the control, as shown here:
<HTML xmlns:control> <HEAD> <title>Behave</title> <style> control\:slider { BEHAVIOR: url(behaviors/slider.htc) } </style> </HEAD> <body> <form method="post" runat="server"> <control:slider onchange="alert(Slider.value)" STYLE="sl--orientation:horizontal"></control:slider> </form> </body> </HTML>
The preceding HTML creates a Slider control that displays the control s value when the user slides the control on a Web form, as shown in Figure 13-12.
Figure 13-12. The Slider behavior
IMPORTANT
Although you can use behaviors that create controls on Web forms, it s usually a better idea to create and use custom controls for tasks that aren t handled by the standard server and HTML controls. Controls created by behaviors are not displayed correctly in the Visual Studio .NET Designer window and don t provide properties and methods that are readily available from server-side code. Custom controls provide both of these advantages.