Chapter 3. Designing Your Web Pages

Provided by:  Imar Spaanjaars

Beginning ASP.NET 4 in C# and VB

This topic contains the following sections.

  • What you will learn in this chapter:
  • Why Do You Need CSS?
  • An Introduction to CSS
  • Working with CSS in Visual Web Developer
  • Practical Tips on Working with CSS
  • Summary
  • Exercises
  • What You Learned in this Chapter

What you will learn in this chapter:

  • What CSS is and why you need it

  • How CSS looks and how to write it

  • The different ways to add CSS code to your ASP.NET pages and to external files

  • The numerous tools that VWD offers you to quickly write CSS

The pages you created in the previous two chapters look pretty plain and dull. That’s because they lack styling information and therefore default to the standard layout that the browser applies. To spruce up your pages, you need a way to change their presentation in the browser. The most common way to do this is by using the Cascading Style Sheets (CSS) language. CSS is the de facto language for formatting and designing information on the Web, including ASP.NET web pages. With CSS you can quickly change the appearance of your web pages, giving them that great look that your design or corporate identity dictates.

Solid support for working with CSS has been added in VWD 2008, the previous version of Visual Web Developer. The new VWD 2010 builds on top of this CSS support and improves it in a number of ways, including the ability to render pages much closer to how they’ll eventually end up in the browser. The CSS tools enable you to visually create your CSS code, making it much easier to style your pages without the need to know or remember every little detail of CSS.

To understand the relevance of and need for CSS in your ASP.NET web sites, you need to understand the shortcomings of HTML first. The next section looks at the problems that plain HTML presents, and how CSS is able to overcome these issues.

Why Do You Need CSS?

In the early days of the Internet, web pages consisted mostly of text and images. The text was formatted using plain HTML, using tags like <strong> to make the text bold, and the <font> tag to influence the font family, size, and color. Web developers soon realized that they needed more power to format their pages, so CSS was created to address some of HTML’s styling shortcomings.

Problems of HTML Formatting

One of the problems with using HTML for formatting is that it offers only a limited set of options to style your pages. You can use tags like <em>, <strong>, and <font> to change the appearance of text and use attributes like bgcolor to change the background color of HTML elements. You also have a number of other attributes at your disposal for changing the way links appear in your page.

Obviously, this feature set isn’t rich enough to create the attractive web pages that your users expect and demand.

Another problem of HTML with a lot more impact on how you build your web pages is the way the styling information is applied to the page. By design, HTML forces you to embed your formatting in your HTML document, making it harder to reuse or change the design later. Consider the following example:

<p><font face=”Arial” color=”red” size=”+1”>
   This is red text in an Arial type face and slightly larger than the default text.
</font></p>

The problem with this code snippet is that the actual data (the text in the <p> element) is mixed with the presentation (the formatting of the text with the <font> tag in this example). Ideally, the two should be separated, so each of them is easier to change without affecting the other.

Imagine you used the <p> and <font> tags to mark up the first paragraph of every page in your site. Clearly, this code is difficult to maintain. What happens when you decide to change the color of the font from red to dark blue? Or what if your corporate identity dictates a Verdana font instead of Arial? You would need to visit each and every page in your site, making the required changes.

Besides maintainability, another problem with HTML formatting is the fact that you can’t easily change the formatting at runtime in the user’s browser. With the HTML from the previous code snippet, there is no way to let your visitor change things like the font size or color, a common request to help people who are visually impaired. If you want to offer your visitors an alternative version of the page with a larger font size or a different color, you’d need to create a copy of the original page and make the necessary changes.

The final problem with HTML formatting is that the additional markup in your page adds considerably to the size of the page. This makes it slower to download and display because the information needs to be downloaded with each page in your web site. It also makes it harder to maintain your pages because you’d need to scroll through large HTML files to find the content you need.

To summarize, formatting with HTML suffers from the following problems:

  • Its feature set severely limits the formatting possibilities that your pages require.

  • Data and presentation are mixed within the same file.

  • HTML doesn’t allow you to easily switch formatting at runtime in the browser.

  • The required formatting tags and attributes make your pages larger and thus slower to load and display.

Fortunately, CSS enables you to overcome all of these problems.

How CSS Fixes Formatting Problems

CSS is designed to format your web pages in almost every possible way. It offers a rich set of options to change every little aspect of your web page, including fonts (size, color, family, and so on), colors and background colors, borders around HTML elements, positioning of elements in your page, and much more. CSS is widely understood by all major browsers today, so it’s the language for visual presentation of web pages and very popular among web developers.

CSS overcomes the problem of mixed data and presentation by enabling you to define all formatting information in external files. Your ASPX or HTML pages can then reference these files and the browser will apply the correct styles for you. With this separation, the HTML document contains what you want to display, and the CSS file defines how you want to display it, enabling you to change or replace one of the two documents, leaving the other unmodified. In addition, CSS can be placed directly in an HTML or ASPX page, which gives you a chance to add small snippets of CSS exactly where you need them. You should be cautious when placing CSS directly in an HTML or ASPX page, because you can then no longer control style information from a single, central location.

Because all CSS code can be placed in a separate file, it’s easy to offer the user a choice between different styles — for example, one with a larger font size. You can create a copy of the external style sheet, make the necessary changes, and then offer this alternative style sheet to the user. You see how this works in Chapter 6 when ASP.NET Themes are discussed.

Another benefit of a separate style sheet file is the decrease in bandwidth that is required for your site. Style sheets don’t change with each request, so a browser saves a local copy of the style sheet the first time it downloads it. From then on, it uses this cached copy instead of requesting it from the server over and over again. Sometimes this caching can work against you when the browser doesn’t download the latest CSS files with your changes. If you find that the browser is not picking up the changes you made to a CSS file, use Ctrl+F5 or Ctl+R in the browser (not VWD) to get a fresh copy from the server.

Now that you have seen why CSS is so important, it’s time to find out how it looks and how to use it.

An Introduction to CSS

In terms of syntax, CSS is an easy language to learn. Its “grammar” consists of only a few concepts. That makes it relatively easy to get started with. What makes CSS a bit more difficult is the way all major browsers render a page. Although virtually every modern desktop browser understands CSS, they all have their quirks when it comes to displaying a page according to the CSS standard. This standard, maintained by the same organization that maintains the HTML standard, the World Wide Web Consortium, or W3C for short, comes in three different versions: 1.0, 2.1, and 3.0. From these three versions, 2.1 is the most applicable today. It contains everything that version 1.0 contains but also adds a lot of possibilities on top of that. It’s also the version that VWD uses and generates by default. Version 3.0 is currently under development and it’s expected to take some time before the major browsers have solid support for it.

Before you look at the actual syntax of CSS, it’s a good idea to see an example first. In the next exercise, you write a simple ASPX page that contains some CSS to format the contents of the page. This helps in understanding the CSS language, which is discussed in full detail in the section that follows.

In this Try It Out you write some CSS that changes the appearance of a header and two paragraphs. You’ll hand code the page for now; the second half of this chapter shows you how to use the CSS tools available in VWD.

  1. In the Demos folder of the Planet Wrox project, create a new Web Form called CssDemo.aspx. For this exercise, it doesn’t matter if you choose inline code or Code Behind.

  2. Make sure the page is in Markup View and then locate the closing </title> tag in the source. Position your cursor at the end of the line and press Enter to create an empty line between the title and head tags. On this new line type the word style and then press Tab. Visual Web Developer completes the <style> element for you. Press Enter twice to create some room between the tags. You end up with the following bolded code:

      <title></title>
      <style type=”text/css”>
    
      </style>
    </head>
    

    Note

    This code completion feature uses code snippets that enable you to associate a piece of code (like the <style> element) with an identifier (like style in this example). Code snippets are very useful to quickly insert pieces of code by typing only the short identifier. Many more code snippets are available, and where appropriate I’ll point them out throughout this book.

    Instead of using the style code snippet, you can also type the full code yourself. Note that as soon as you type the opening angle bracket (<), a list pops up that enables you to select the <style> tag. The same applies to the type attribute; simply type the letters ty and the type attribute is preselected in the list. All you need to do to complete the word is press the Tab or Enter key. And, once more, the same help is available for the attribute value text/css. Simply select it in the list and press Tab or Enter, and the value is inserted for you automatically, nicely surrounded by the double quotes.

  3. Next, between the opening and closing <style> tags, type the following bolded CSS code:

    <style type=”text/css”>
      h1
      {
        font-size: 20px;
        color: Green;
      }
    
      p
      {
        color: Blue;
        font-style: italic;
      }
    
      .RightAligned
      {
        text-align: right;
      }
    </style>
    

    Take great care when typing this code, because CSS is rather picky about syntax. The first item in the list is an h1 tag to style a heading at the first level so it gets a size of 20 pixels and is displayed in a green font. Notice the colon between font-size and 20px and that the line is closed with a semicolon.

    The second item in the list simply contains the letter p and defines the look and feel for all <p> elements in the page.

    The last item is prefixed with a period (.) followed by the text RightAligned. This item is used to right-align some text in the page.

  4. Scroll down in the page a bit until you see the opening <div> tag. Right after this tag, type the following bolded code:

    <div>
      <h1>Welcome to this CSS Demo page</h1>
      <p>CSS makes it super easy to style your pages.</p>
      <p class=”RightAligned”>
        With very little code, you can quickly change the looks of a page.
      </p>
    </div>
    

    Instead of typing in this code directly, you can also use the Formatting toolbar while in Design View to create elements like <h1> and <p>. For now, you’ll need to switch to Markup View to add class=”RightAligned”, but in later exercises in this chapter you see how you can have the IDE write this code for you.

  5. If you switch to Design View (or Split View), you’ll see that the designer shows your text with the formatting defined in the <style> element of the page. Figure 3-1 shows the page in Split View so you can see the code and the design at the same time.

    Beginning ASP.NET4 in C# and Visual Basic

    Figure 3-1

    Although this black and white book makes it difficult to see different font colors, in Figure 3-1 you can clearly see that the <h1> has a larger font size. The figure also shows that all paragraphs (both the plain paragraph and the one with class=”RightAligned”) are now displayed with an italic font. Finally, you can see that the final paragraph is aligned to the right of the window, because the class attribute on the tag is set to RightAligned.

    If you don’t see the last paragraph glued to the right border of the Document Window, make sure you typed RightAligned exactly the same in the <style> tag and in the class attribute. Because CSS is case sensitive, there’s a big difference between RightAligned and rightaligned.

  6. Press Ctrl+F5 to view CssDemo.aspx in your browser. The page you see in the browser is identical to the preview you got in the Design View of Visual Web Developer.

Although the code you typed in this exercise is relatively simple, there’s a lot going on under the hood of the browser (and the Design View of VWD 2010) to make this possible. You started by adding some styles to the <head> section of the page:

<style type=”text/css”>
  h1
  {
    font-size: 20px;
    color: Green;
  }
 
  ...
</style>

The <style> tag is used to wrap a style sheet that is embedded in the page with its type attribute set to text/css. The code block from h1 until the closing curly brace (}) between the <style> tags is called a rule set or simply a rule. The rule in this code snippet defines the appearance for all <h1> elements in your page. The h1 at the top of the code block is called a selector and is used to indicate to what element the formatting should be applied. In this case, the selector maps directly to an HTML element, but many other selectors are available, as you’ll see in the next section. Figure 3-2 shows how the elements are related to each other.

Beginning ASP.NET4 in C# and Visual Basic

Figure 3-2

Between the curly braces you see the style information that should be applied to the heading. Each line between the curly braces is called a declaration. A declaration consists of a property, followed by a colon and then followed by a value. The semicolon (;) at the end of a declaration separates it from the next declaration and is required on all declarations except for the last one in the rule set. However, for consistency, it’s a good idea to add it to all declarations, which is what I’ll do in the remainder of this book.

When the browser loads this page, it also reads in the styles you defined between the <style> tags. Then, whenever it comes across an HTML element that matches the selector, it applies the CSS rules to that element. So, for the <h1> and <p> elements, their respective rules are applied. This causes the heading to turn green with a large font, while the paragraphs turn blue with an italic font.

But why does the last paragraph turn blue and get right-aligned? In CSS, you can have rules coming from different sources. The last <p> tag gets its style information from the standard p selector in the style definition. So, the p rule gives the paragraph a blue and italic font. However, it also has a class defined. This class, called RightAligned, causes the text to be aligned to the right of the window. In the end, the last <p> element gets its rules from two selectors at the same time. You can make up and assign your own class names (as shown with the RightAligned class), giving you the flexibility to design your pages and elements exactly how you want them.

The next section digs a lot deeper in the syntax of CSS, giving you a much more detailed view on selectors, properties, and values.

CSS—The Language

As you saw in the previous Try It Out exercise, a cascading style sheet is actually a collection of rules. A rule is a combination of a selector and one or more declarations, which in turn can be broken down to a property and a value. You’re probably getting a little dizzy from all the new terms that were introduced in the past few paragraphs, so in the next section, you see most of them again, with a detailed explanation and code examples that show you what they are used for and how they work.

The Style Sheet

The style sheet contains all the relevant style information that should be applied to page elements. In its simplest form, a style sheet looks like this:

h1
{
  color: Green;
}

A style sheet can also contain more than one rule as you saw in the previous exercise. At the same time, each rule can contain multiple declarations, enabling you to group them under a single selector:

h1
{
  font-size: 20px;
  color: Green;
}

The code you just saw is functionally identical to this:

h1
{
  font-size: 20px;
}
h1
{
  color: Green;
}

The condensed form, where the two declarations are grouped under the same selector, is much easier to read, understand, and maintain, so it’s advisable to use this syntax as much as possible.

To be able to style an element on a page, a browser has to know three things:

  • What element of the page must be styled?

  • What part of that element must be styled?

  • How do you want that part of the selected element to look?

The answers to these questions are given by selectors, properties, and values.

Selectors

As its name implies, a selector is used to select or point to one or more specific elements within your page. A number of different selectors are available, giving you fine control over what elements you want to style. The selector answers the first question: What element of the page must be styled? The next section shows you the four most important types of selectors.

The Universal Selector

The Universal selector, indicated by an asterisk (*), applies to all elements in your page. The Universal selector can be used to set global settings like a font family. The following rule set changes the font for all elements in your page to Arial:

{
  font-family: Arial;
}

The Type Selector

The Type selector enables you to point to an HTML element of a specific type. With a Type selector, all HTML elements of that type will be styled accordingly.

h1
{
  color: Green;
}

This Type selector now applies to all <h1> elements in your code and gives them a green color. Type selectors are not case sensitive, so you can use both h1 and H1 to refer to the same heading.

The ID Selector

The ID selector is always prefixed by a hash symbol (#) and enables you to refer to a single element in the page. Within an HTML or ASPX page, you can give an element a unique ID using the id attribute. With the ID selector, you can change the behavior for that single element, like this:

#IntroText
{
  font-style: italic;
}

Because you can reuse this ID across multiple pages in your site (it only has to be unique within a single page), you can use this rule to quickly change the appearance of an element that you use once per page, but more than once in your site, for example with the following HTML code:

<p id=”IntroText”>I am italic because I have the right ID.</p>
<p id=”BodyText”>I am NOT italic because I have a different ID.</p>

In this example, the #IntroText selector changes the font of the first paragraph — which has the matching id attribute — but leaves the other paragraph unmodified. ID selectors are case sensitive, so make sure that the id attribute and the selector always use the same casing.

The Class Selector

The Class selector enables you to style multiple HTML elements through the class attribute. This is handy when you want to give the same type of formatting to a number of unrelated HTML elements. The following rule changes the text to red and bold for all HTML elements that have their class attributes set to Highlight:

.Highlight
{
  font-weight: bold;
  color: Red;
}

The following code snippet uses the Highlight class to make the contents of a <span> element and a link (<a>) appear with a bold typeface:

This is normal text but <span class=”Highlight”>this is Red and Bold.</span>
This is also normal text but 
   <a href=”CssDemo.aspx” class=”Highlight”>this link is Red and Bold as well.</a>

Notice that the selector uses a period in its name, but you don’t use this period when referring to the selector in the class attribute. The class attribute is very useful because it enables you to reuse a piece of CSS for many different purposes, regardless of the HTML element that uses the class.

CSS supports more types of selectors, giving you even more control over the elements you want to target, but the four different types you just saw are the most widely used.

Grouping and Combining Selectors

CSS also enables you to group multiple selectors by separating them with a comma. This is handy if you want to apply the same styles to different elements. The following rule turns all headings in the page to red:

h1, h2, h3, h4, h5, h6
{
  color: Red;
}

Moreover, with CSS you can also combine selectors, enabling you to hierarchically point to a specific element in a page. You can do this by separating the selectors with a space. The following example targets all <p> elements that fall within an element with an id of MainContent, leaving all other paragraphs unmodified.

#MainContent p
{
  font-size: 18px;
}

Note that combining is very different from grouping. Grouping is just a shortcut to avoid typing the same declarations over and over again, whereas combining enables you to target specific elements in your document.

With combining, you’re not limited to ID and Type selectors; you can also use it with the other selectors, as is demonstrated with the following example:

#MainContent p.Attention
{
  font-weight: bold;
}

This rule changes all paragraphs with the class Attention within the element with its id set to MainContent and leaves all others untouched. The following HTML snippet uses this rule to show the effect:

<div id=”MainContent”>
  <p class=”Attention”>My class is Attention, so my text is bold.</p>
  <p>My text is not bold, as it lacks the Attention class.</p>
</div>
<p class=”Attention”>I am NOT bold because I don’t fall within MainContent.</p>

The second question that needs to be answered to apply a certain style in your page is about what part of the element must be styled. This is done with properties.

Properties

Properties are the part of the element that you want to change with your style sheet. The CSS specification defines a long list of properties (VWD’s IntelliSense list shows more than 100 items), although you won’t use all of them in most web sites. The following table lists some of the most common CSS properties and describes where they are used.

Property

Description

Example

background-colorbackground-image

Specifies the background color or image of an element.

background-color: White;background-image: url(Image.jpg);

border

Specifies the border of an element.

border: 3px solid black;

color

Changes the font color.

color: Green;

display

Changes the way elements are displayed, enabling you to hide or show them.

display: none;This causes the element to be hidden, and not take up any screen space.

float

Enables you to “float” an element in the page using a left or right float. Other content is then placed on the opposite side.

float: left;This setting causes other content following a float to be placed at the top-right corner of the element. You see how this works later in the chapter.

font-familyfont-sizefont-stylefont-weight

Changes the appearance of fonts used on your page.

font-family: Arial;font-size: 18px;font-style: italic;font-weight: bold;

heightwidth

Sets the height or width of elements in your page.

height: 100px;width: 200px;

marginpadding

Sets the amount of free space inside (padding) and outside (margin) of an element.

padding: 0;margin: 20px;

visibility

Controls whether an element is visible in the page. Invisible elements still take up screen space; you just don’t see them.

visibility: hidden;This causes the element to be invisible. However, it still takes up its original space in the page. It’s as if the element is still there, but completely transparent.

Fortunately, VWD helps you to find the right property with its many CSS tools, so you don’t have to remember them all.

Note

Many more selectors and properties are available in CSS than I have described here. For more detail on CSS, consult VWD’s IntelliSense lists or take a look at www.w3schools.com/css/css_reference.asp.

For a property to be useful, you need to give it a value, which answers the third question: How do you want the part of the selected element to look?

Values

Just as with properties, values come in many flavors. The values you have available depend on the property. For example, the color attribute takes values that represent a color. This can be a named color (such as White), or a hexadecimal number representing a red, green, and blue (RGB) component (such as #FF0000), or it can be set using the CSS rgb notation. The following examples are all functionally equivalent:

h1
{
  color: Red;
}

h1
{
  color: #FF0000;
}

h1
{
  color: rgb(100%, 0%, 0%);
}

The first declaration uses the named color Red, whereas the other two examples use an RGB value to specify the red color. Using named colors can increase the readability of your CSS code, but because you’re limited to a relatively short list of named colors, you often need the hexadecimal notation to get the exact color you want. When you type a color property in VWD, it presents you with a list of known colors as shown in Figure 3-3. If you want to type in a different color, simply ignore the list (or close it by pressing the Escape key) and then type your own value. In a later exercise in this chapter you see how to use a color picker to select non-standard colors.

Beginning ASP.NET4 in C# and Visual Basic

Figure 3-3

Many other values are possible as well, including size units (px, em, and so on), font families, images (which take the form of url(SomeImage.jpg)), or so-called enumerations like the border-style, which allows you to set a border style to solid, dashed, double, and so on.

Using Shorthand

Many of the CSS properties enable you to write a shorthand version as well as a more expanded version. Take, for example, the border property. In its shortest form, the border property can be set like this:

border: 1px solid Black;

This border property applies a border to all four sides of an HTML element. The border size will be 1px, the style will be solid (some of the other options include dashed, dotted, and double), and the border color will be set to Black.

This is an easy way to quickly set all four borders of the HTML to the same values. However, if you want more control over the individual borders and their properties, you can use the expanded version:

  border-top-width: 1px;
  border-top-style: solid;
  border-top-color: Black;
  border-right-width: 1px;
  border-right-style: solid;
  border-right-color: Black;
  border-bottom-width: 1px;
  border-bottom-style: solid;
  border-bottom-color: Black;
  border-left-width: 1px;
  border-left-style: solid;
  border-left-color: Black;

This long version causes the exact same style to be applied: a solid black border on all four sides with a thickness of 1 pixel. In most cases, you should favor shorthand notation over its expanded counterpart, because it’s much easier to read and maintain. However, if you need absolute control over the border — for example, if you want a 2-pixel dashed border on the left and top sides, and a green, solid border on the right and bottom sides of the HTML element — it’s good to know that you can set each border property of all four directions individually.

Other CSS properties that support shorthand include font, background, list-style, margin, and padding. If you’re unsure whether a property supports shorthand, consult the IntelliSense pop-up list that appears by pressing Ctrl+Space when you’re entering a property in a CSS file or a <style> block.

Although at times it seems you need to write CSS by trial and error, and just hope for the right result, there’s actually a quite accurate model behind CSS that determines how items should be laid out on the page. This model is called the CSS Box Model.

The CSS Box Model

The CSS Box Model describes the way three important CSS properties are applied to HTML elements: padding, border, and margin. Figure 3-4 shows a graphical representation of the box model.

Beginning ASP.NET4 in C# and Visual Basic

Figure 3-4

In the middle there is an HTML element like a <p> or a <div> with a certain height and width. Just around it there is padding; the whitespace that surrounds the element within its border. Immediately after the padding you can see the border and finally on the outside there is margin, which defines the room between an element (including its padding and border) and its surrounding elements. The three outer properties of an element — padding, border, and margin — add up to the space that an element takes up in page. To see how this works, consider the following CSS and HTML:

.MyDiv
{
  width: 200px;
  padding: 10px;
  border: 2px solid black;
}
...
<div class=”MyDiv”>Element</div>

This renders a rectangle in the browser with the <div> element surrounded by a black border of two pixels shown in Figure 3-5.

Beginning ASP.NET4 in C# and Visual Basic

Figure 3-5

Before you read on, try answering the question: How wide is the arrow below the <div> element?

If you guessed 224 pixels, you are correct. The width of the arrow is the sum of three values: the width of the actual element (200 pixels), plus the width of the padding surrounding it on both sides (two times 10 pixels), plus the width of the borders on both sides (two times two pixels), resulting in a total width of 224 pixels. So, if you wanted the entire box to be 200 pixels wide instead, you’d need to set the width property of the MyDiv selector to 176px.

The example shows the effect on the width only, but the same principles apply to the height of elements. Keep this box model in mind when laying out your pages. When things end up wider or taller than you anticipated, check the width, height, padding, border, and margin properties in the CSS style sheet.

In the next exercise, you modify the site’s home page that you created in the previous chapter. You add the basic layout for the site, which is then styled using a style sheet. In Chapter 6 you use this page again when you upgrade it to a master page.

In this exercise you modify two files: First, you add the basic layout elements to the Default.aspx page to create room for a header, a menu, the main content area, a sidebar, and a footer. Then you modify the Styles.css file from the Styles folder to change the size and location of these elements. Finally, you attach the style sheet to the page, so the style information is applied when the page is viewed in the designer or in a browser.

  1. Open the file Default.aspx from the root of your web site and if necessary switch to Markup View.

  2. Modify the code within the <form> element so it ends up like this:

    <form id=”form1” runat=”server”>
      <div id=”PageWrapper”>
        <div id=”Header”>Header Goes Here</div>
        <div id=”MenuWrapper”>Menu Goes Here</div>
        <div id=”MainContent”>
          <h1>Hi there visitor and welcome to Planet Wrox</h1>
          ... 
        </div>
        <div id=”Sidebar”>Sidebar Goes Here</div>
        <div id=”Footer”>Footer Goes Here</div>
      </div>
    </form>
    

    Make sure that the welcome message you added in the previous chapter ends up between the opening and closing tag of the MainContent<div>.

  3. Open the file Styles.css from the Styles folder. If you added some code to this file earlier, remove that code first.

  4. At the top of the page, type the following code that uses an ID selector to select the Header<div>:

    #Header
    {
    
    }
    
  5. Position your mouse between the curly braces and then choose Styles | Build Style from the main menu. Alternatively, you can choose the same item by right-clicking the ID selector, or clicking the Build Style button on the Styles toolbar. The Modify Style dialog box shown in Figure 3-6 appears.

    Beginning ASP.NET4 in C# and Visual Basic

    Figure 3-6

  6. In the Category list on the left, click Background and then open the drop-down list for the background color. From the color picker that appears, click the Silver color, as shown in Figure 3-7.

    Alternatively, you can type the hexadecimal color code for Silver (#C0C0C0) in the background-color text box directly.

    Beginning ASP.NET4 in C# and Visual Basic

    Figure 3-7

  7. Switch to the Position category by clicking it in the list on the left. The panel that appears enables you to set position-related information, including the height and width. Under width, enter 844 and make sure that px is selected in the drop-down list at the right. For the height, enter 86. Click OK to dismiss the dialog box and to insert the declarations into your code, which now looks like this:

    #Header
    {
      background-color: #C0C0C0;
      width: 844px;
      height: 86px;
    }
    
  8. Repeat steps 4 through 7, this time creating the following rules:

    {
      font-family: Arial;
    }
    
    h1
    {
      font-size: 20px;
    }
    
    #PageWrapper
    {
      width: 844px;
    }
    
    #MenuWrapper
    {
      width: 844px;
    }
    
    #MainContent 
    {
      width: 664px;
      float: left;
    }
    
    #Sidebar 
    {
      background-color: Gray;
      width: 180px;
      float: left;
    }
    
    #Footer
    {
      background-color: #C0C0C0;
      width: 844px;
      clear: both;
    }
    

    The float and clear properties are found in the layout category of the Modify Style dialog box.

  9. When you’re done creating the rules, save and close the Styles.css file, because you’re done with it for now.

  10. 10.Open the file Default.aspx again and switch to Design View. From the Solution Explorer, drag the file Styles.css from the Styles folder onto the page. You should immediately see the Design View change to reflect the code you wrote in the style sheet. When you dropped the style sheet on the page, VWD inserted code in the <head> section of the page in Markup View that attaches the style sheet to the document:

    <head runat=”server”>
      <title></title>
      <style type=”text/css”>
        .style1
        {
          color: #FF0000;
        }
      </style>
      <link href=”Styles/Styles.css” rel=”stylesheet” type=”text/css” />
    </head>
    

    You can also drag an existing style sheet from the Solution Explorer directly in the <head> section of a page in Markup View. When you do that, VWD adds the same <link> element.

  11. Finally, save the changes to all open documents (press Ctrl+Shift+S) and then request Default.aspx in your browser. Your screen should look similar to Figure 3-8, which shows the page in Mozilla Firefox.

    Beginning ASP.NET4 in C# and Visual Basic

    Figure 3-8

The Style Builder makes it easy to select CSS properties and change their values. You don’t need to memorize every little detail about CSS, but instead you can visually create your CSS code. Although the tool can do most of the work for you, it’s still useful if you can read and understand the CSS code. When you need to make tweaks to your code, it’s often quicker to do it directly in the Document Window, instead of opening the Style Builder.

Note that the Header, PageWrapper, MenuWrapper, and Footer have an exact width of 844 pixels. This way, the site fits nicely on screens with a size of 1024  768 pixels, a common screen size for many of today’s computers, without being squeezed between the Windows borders. Systems with bigger screens will simply expand the white background at the right of the page.

Note also that the MainContent area and the Sidebar are positioned next to each other. This is done with the CSS float property:

#MainContent 
{
  width: 664px;
  float: left;
}

#Sidebar 
{
  background-color: Gray;
  width: 180px;
  float: left;
}

This tells the MainContent to “float” on the left side of the Sidebar, effectively placing the Sidebar to the right of it. You need to tell the Sidebar to float as well; if you leave it out, it will be placed at the left of the page, right where it was before you applied the CSS.

The combined width of the two elements adds up to 844 pixels, which is exactly the width of their parent element: the PageWrapper.

To end the float and tell the Footer element to be placed directly under the MainContent and Sidebar elements, the clear property is used to clear any float (left or right) that may be in effect:

#Footer
{
  background-color: #C0C0C0;
  width: 844px;
  clear: both;
}

The gray backgrounds are just temporarily added to the code, so it’s easier to see what <div> ends up where. In future exercises, you modify the CSS file again to fit the scheme of the Planet Wrox web site.

To tell the browser what styles to apply, you link the style sheet in the head of the page:

<link href=”Styles/Styles.css” rel=”stylesheet” type=”text/css” />

This tells the browser to look in the Styles folder for a file called Styles.css and apply all rules in that file to the current document. Once the browser has downloaded the CSS file, it applies all the styles it finds in there to your HTML elements, resulting in the layout shown in Figure 3-8.

In this exercise, you saw how to link a style sheet to a page using the <link> tag. There are, however, more ways to include style sheets in your web pages.

Adding CSS to Your Pages

The first way to add CSS style sheets to your web pages is through the <link> element that points to an external CSS file, as you saw in the previous exercise. Take a look at the following <link> to see what options you have when embedding a style sheet in your page:

<link href=”StyleSheet.css” rel=”Stylesheet” type=”text/css” media=”screen” />

The href property points to a file within your site, just as you saw in the previous chapter when you created links between two pages. The rel and type attributes tell the browser that the linked file is in fact a cascading style sheet. The media attribute is quite interesting: it enables you to target different devices, including the screen, printer, handheld devices, and even Braille and aural support tools for visually impaired visitors. The default for the media attribute is screen, so it’s OK to omit the attribute if you’re targeting standard desktop browsers.

You briefly saw the second way to include style sheets at the beginning of this chapter: using embedded <style> elements. The <style> element should be placed at the top of your ASPX or HTML page, between the <head> tags. Within the <style> tags, you can write the exact same CSS you saw earlier. For example, to change the appearance of an <h1> element in the current page alone, you can add the following code to the <head> of your page:

<head runat=”server”>
  <title></title>
  <style type=”text/css”>
    h1
    {
      color: Blue;
    }
  </style>
</head>

The third way to apply CSS to your HTML elements is to use inline styles with the style attribute that you saw in the previous chapter. Because the style attribute is already applied to a specific HTML element, you don’t need a selector and you can write the declaration in the attribute directly:

<span style=”color: White; background-color: Black;”>
    This is white text on a black background.
</span>

Choosing among External, Embedded, and Inline Style Sheets

Because you have so many options to add style sheets to your site, what’s the best method to use? In general, you should give preference to external style sheets over embedded styles, which in turn are preferred over inline styles. External style sheets enable you to change the appearance of the entire site through a single file. Make one change to your external style sheet file, and all pages that use this style sheet pick up the change automatically.

However, it’s perfectly acceptable to use embedded and inline styles as well in certain circumstances. If you want to change the look of a single page, without affecting other pages in your site, an embedded style sheet is your best choice. The same applies to inline styles: if you only want to change the behavior of a single element in a single page, and you’re pretty sure you’re not going to need the same declaration for other HTML elements, use an inline style.

An important thing to consider is the way that the various types of style sheets override each other. If you have multiple identical selectors with different property values, the one defined last takes precedence. For example, consider a rule defined in an external style sheet called Styles.css that sets the color of all <h1> tags to green:

h1
{
  color: Green;
}

Now imagine you’re attaching this style sheet in a page that also has an embedded rule for the same h1 but that sets a different color:

  <link href=”Styles/Styles.css” rel=”stylesheet” type=”text/css” />
  <style type=”text/css”>
    h1
    {
      color: Blue;
    }
  </style>

With this code, the color of the actual <h1> tag in the page will be blue. This is because the embedded style sheet that sets the color to blue is defined later in the page and thus overrides the setting in the external file. If you turn the styles around like this:

  <style type=”text/css”>
    h1
    {
      color: Blue;
    }
  </style>
  <link href=”Styles/Styles.css” rel=”stylesheet” type=”text/css” />

the heading will be green, because the setting in the external style sheet now overrules that of the embedded style.

The same principle applies to inline style sheets. Because they’re defined directly on the HTML elements, their settings take precedence over embedded and external style sheets.

It’s also good to know that CSS generally overrules attributes on HTML elements. For example, if you have a CSS rule that sets the width and height of an image, the height and width attributes on the img element are ignored and the image in this example ends up as a 100-pixel square:

img
{
  height: 100px;
  width: 100px;
}
...
<img src=”SomeImage.jpg” width=”200px” height”200px” />

Note

There’s a lot more to CSS than what is shown here. To learn more about CSS, pick up a copy of Professional ASP.NET 2.0 Design: CSS, Themes, and Master Pages by Jacob J. Sanford (ISBN: 978-0-470-12448-2) or a copy of Beginning CSS: Cascading Style Sheets for Web Design, Second Edition by Richard York (ISBN: 978-0-470-09697-0).

In general, it’s recommended that you attach external files at the top of the <head> section, followed by embedded style sheets. That way, the external file defines the global look of elements, and you can use embedded styles to overrule the external settings.

VWD makes it easy to move embedded style sheets to an external CSS file, something you learn how to do in the next section, which discusses the remainder of the CSS tools in VWD.

Working with CSS in Visual Web Developer

VWD has the following handy tools on board for working with CSS:

  • The Style Sheet toolbar, giving you quick access to creating new rules and styles.

  • The CSS Properties Grid, which enables you to change property values.

  • The Manage Styles window, enabling you to organize styles in your site, changing them from embedded to external style sheets and vice versa; reorder them; link existing style sheets to a document; and create new inline, embedded, or external style sheets.

  • The Apply Styles window, which you can use to choose from all available styles in your site and quickly apply them to elements in your page.

  • The Style Builder, which you can use to visually create declarations.

  • The Add Style Rule window, which helps in building more complex selectors.

The next sections give you a detailed look at these six tools.

Creating New Styles in External Style Sheets

In an earlier Try It Out, you manually added selectors to the CSS file and then used the Style Builder to write the rules. However, you can also use the VWD tools to write the selectors for you. In the next Try It Out, you see how to use the Add Style Rule window to create a new rule in an external file. You then use the Style Builder to modify the rule.

In this exercise, you create a new style that affects all the links in the MainContent area. By using combined selectors, you can target the links in the content area only, leaving the others unmodified.

  1. Start by opening the file Styles.css from the Styles folder.

  2. Scroll down in the file and position your cursor at the end, right below the #Footer rule.

  3. Make sure the Style Sheet toolbar is visible and click the first button, labeled Add Style Rule, or choose Styles | Add Style Rule from the main menu. With the dialog that appears you can visually create a combined selector. In the left section of the dialog box, you can choose among Element, Class, and ID selectors.

    Beginning ASP.NET4 in C# and Visual Basic

    Figure 3-9

    Select the last option, labeled Element ID, and in its text box type MainContent. Your dialog now looks like Figure 3-9.

    If you don’t see the hash symbol (#) in front of MainContent in the Style Rule Preview box, make sure you selected Element ID and not Element. Click the button with the right arrow in the middle of the screen to add the selector to the Style Rule Hierarchy list.

  4. Next, select the Element radio button at the top of the dialog box and from its drop-down list, choose a (for links) and click the arrow button once more. Your screen should now show a preview of the selector in the Style Rule Preview box, as in Figure 3-10.

    Beginning ASP.NET4 in C# and Visual Basic

    Figure 3-10

  5. Click OK to add the selector to your style sheet file. You should end up with the following empty rule:

    #MainContent a
    {
    }
    
  6. Right-click between the curly braces of the rule you just inserted and choose Build Style.

  7. In the Font category, change the color property to #008000 by clicking the arrow of the drop-down list box, and then clicking the green square on the top row.

  8. In the text-decoration section at the right of the same dialog box, place a check mark for the underline option. The Modify Style dialog box should now look like the one shown in Figure 3-11.

    Beginning ASP.NET4 in C# and Visual Basic

    Figure 3-11

  9. Click OK to dismiss the dialog box. Back in the CSS file, select the entire rule set you just created (including #MainContent a and both curly braces), copy it to the clipboard, and then paste it again twice below the original rule set.

  10. Rename the first selector you just pasted from #MainContent a to #MainContent a:visited. This style is used for links that the user has already visited.

  11. Right-click the new rule you just created and choose Build Style. In the Font category, change the color from green to red by typing #FF0000 in the color text box and click OK.

  12. Change the third selector in the file from #MainContent a to #MainContent a:hover. This style is applied to links when the user hovers over them with the mouse.

  13. Once again, right-click the new selector you just created and choose Build Style. In the Font category, change the color from green to orange by typing #FFA500 in the color text box. Click OK to close the Modify Style dialog box.

    You should end up with the following three rules in your CSS file below the styles that were already present:

    #MainContent a
    {
      color: #008000;
      text-decoration: underline;
    }
    
    #MainContent a:visited
    {
      color: #FF0000;
      text-decoration: underline;
    }
    
    #MainContent a:hover
    {
      color: #FFA500;
      text-decoration: underline;
    }
    

You started off by creating a new rule using the Add Style Rule dialog box. Quite often, you’ll find it easier and quicker to type the rule directly in the code editor. However, when you’re creating complex combined rules, the Add Style Rule dialog box can help you understand and create the hierarchy of the rule.

The Modify Style dialog box is an excellent tool for creating new CSS declarations. Instead of memorizing all the different CSS properties and values, you can simply point and click them together in an organized dialog box. All the different CSS properties are grouped under logical categories, making it easy to find and change them.

The :hover and :visited parts on the a selector are probably new to you. These selectors are called pseudo class selectors. The a:visited selector is only applied to links that you have already visited in your browser. The a:hover selector is only applied to the <a> tag when the user hovers the mouse over the link. In the next Try It Out you see the effect of these two selectors in the browser.

With the style sheet created, the next thing you need to do is attach this style sheet to your document. You have a number of ways to do this, including typing in the code by hand or dropping the file in Markup or Design View. The next Try It Out exercise shows you a third option: using the Manage Styles window.

In this exercise, you remove and reattach the style sheet called Styles.css to your Default.aspx page so you see another alternative to attaching a style sheet file to an ASPX page. You then add some text and links to this page so you can see the behavior of rule sets you created earlier.

  1. Switch the page Default.aspx into Markup View and remove the <link /> element from the <head> section that you added earlier in this chapter. Then switch to Design View and make sure the Manage Styles window is open. If it isn’t, click somewhere in the Document Window to activate the Design View and then choose View | Manage Styles from the main menu. The window shown in Figure 3-12 appears. Recall from Chapter 1 that if you don’t see this item in the View menu, choose Tools | Settings | Expert Settings first.

    Beginning ASP.NET4 in C# and Visual Basic

    Figure 3-12

    The Manage Styles window gives you an overview of all external and embedded style sheets that apply to the current document. Notice how VWD sees that the current document already contains an embedded style: style1 that you created in Chapter 2.

  2. Click the Attach Style Sheet button on the Manage Styles window (it’s the second button in Figure 3-12), browse to your Styles folder in the root of the site, and select the Styles.css file. Click OK and the style sheet is inserted in your page again.

  3. When you attach the style sheet, the Manage Styles window (shown in Figure 3-13) is updated and now shows your newly attached style sheet.

    Beginning ASP.NET4 in C# and Visual Basic

    Figure 3-13

  4. With the page Default.aspx still open in Design View, select the text “look around” in the paragraph. If you typed something else in an earlier Try It Out, select that text instead. At this stage, all that’s important is that you have some text to turn into a link.

  5. On the Formatting toolbar, click the Convert to Hyperlink button (with the globe and link symbol on it), click the Browse button in the dialog box that appears, and select Default.aspx in the root of the site. This way, the link points to the same page it’s defined in, which is fine for this exercise. Click OK twice to dismiss the dialog boxes.

  6. Save the changes to all open documents (choose File | Save All from the main menu or press Ctrl+Shift+S) and then request Default.aspx in your browser by pressing Ctrl+F5. You should see the page appear with the “look around” link underlined, as shown in Figure 3-14.

    Beginning ASP.NET4 in C# and Visual Basic

    Figure 3-14

  7. Hover your mouse over the “look around” link; note that it turns to orange.

  8. Click the “look around” link, and the page will reload. The link has now turned to red. If the link was already red the first time you visited it, don’t worry. You opened the page in your browser before, which caused the browser to mark the link as visited. The browser keeps track of the pages you visit and then applies the correct style to new and visited links. If you want to see the desired behavior in Internet Explorer, open up the Internet Options by choosing Tools | Internet Options. Then on the General tab, click the Delete button. In the dialog box that pops up, clear the history by following the on-screen instructions. When you now reload the page by pressing Ctrl+F5 in your browser, the link should turn to green. Other browsers have similar options to clear the browser’s history. For example, Firefox enables you to clear the history using the Tools | Clear Recent History menu option. If you don’t have this menu item, choose Tools | Options and then switch to the Privacy tab, where you can delete the history as well.

    Alternatively, you can open the page in a different browser. To select an alternate browser, right-click Default.aspx in the Solution Explorer and choose Browse With from the context menu. If your alternate browser is listed there already, select it from the list and then click Browse. Optionally you can make this browser your default, by clicking the Set as Default button.

    If your browser is not listed, click the Add button and then the ellipsis next to the Program Name box to search for your favorite browser. When the browser is displayed in the list, click it to select it and then click Browse to open the page in that browser. The page should now appear in your alternate browser.

The Manage Styles window gives you a quick overview of style sheets that are active for the current page, either as an external and attached style sheet, or as an embedded style sheet in the <head> section of the page. It’s a very useful window to attach new styles to the current document, and to move styles from one location to another, which you see how to do in the next section. When you open the page in the browser, the updated style sheet is downloaded and the browser then applies the #MainContent a:visited selector to all links to pages you visited before. When you hover your mouse over a link, the selector #MainContent a:hover is applied, causing the link to turn orange.

Viewing your pages in different browsers is a good thing to do. Although modern browsers tend to render a page more and more similarly, there are subtle differences that you need to be aware of and handle in your HTML and CSS code. Installing a few different browsers on your system (Internet Explorer, Firefox, Safari, Opera, and Chrome, for example), assigning them to the Browse With dialog as shown in this Try It Out, and testing your pages in these browsers as often as you can will help to ensure your pages look exactly right in the majority of the browsers.

Useful as external style sheets may be, there are times when you really want to use embedded or inline styles instead. Creating and managing those styles, explained in the next section, is just as easy.

Creating Embedded and Inline Style Sheets

When you’re working with a page in Design View, you often need to make minor tweaks to part of the page, like styling a piece of text, aligning an image, or applying a border to an element. At this stage, you need to make a decision about whether to create an inline, embedded, or external style sheet. As you saw earlier, you should opt for external or embedded style sheets if you envision you’re going to reuse a style later. VWD doesn’t care much, though. It enables you to create styles at all three levels. Even better, it enables you to easily upgrade an embedded style to an external one, or copy inline style information to a different location, giving you great flexibility and the option to change your mind later.

In the next exercise, you see how to create inline and embedded style sheets. You see later how to move those styles to an external style sheet, enabling other pages to reuse the same styles.

In this Try It Out, you add a style rule to the <h1> element of the page, to remove the default margin that a browser draws around the heading. In addition, you style the first paragraph using a class, giving it a different look to make it stand out from the other paragraphs on the page.

  1. Go back to VWD and make sure that the page Default.aspx is open in Design View.

  2. Click once on the h1 element in the Document Window to select it and then choose Format | New Style. The New Style dialog box appears (visible in Figure 3-15), which is pretty similar to the Modify Style dialog box you saw earlier.

  3. At the top of the screen, open the Selector drop-down list and choose (inline style). It’s the first item in the list. This ensures that the new style is applied as an inline style to the <h1> element.

  4. Switch to the Box category, shown in Figure 3-16.

    Figure 3-15

    Beginning ASP.NET4 in C# and Visual Basic

    Figure 3-16

    This dialog box has a handy diagram that serves as a refresher on the CSS Box Model, showing you where the properties padding, border, and margin end up.

    By default, browsers draw some white space above or below an <h1> element, but the actual amount differs between browsers. To give each browser the same consistent settings, you can reset the padding to 0 and then apply a little bit of margin at the bottom of the heading, which creates some distance to the elements following it. To do this, set padding to 0 in the top box. By leaving the Same for All option selected, VWD creates a shorthand declaration for you. Then uncheck Same for All for the margin section, enter 0 for the top, right, and left boxes and enter 10 for the bottom text box. Leave all drop-down lists set to px and click OK. You end up with the following <h1> element with an inline style in Markup View:

    <h1 style=”padding: 0px; margin: 0px 0px 10px 0px”>
      Hi there visitor and welcome to Planet Wrox
    </h1> 
    
  5. Next, in Design View, select the first paragraph by clicking it. A small glyph appears to indicate you selected a <p> element, as visible in Figure 3-17. The Tag Selector at the bottom of the Document Window should highlight the <p> element.

    Beginning ASP.NET4 in C# and Visual Basic

    Figure 3-17

  6. With the paragraph still selected, choose Format | New Style from the main menu. This time, instead of creating an inline style, type the text .Introduction in the Selector box that is visible in Figure 3-18. Don’t forget the dot (.) in front of the selector’s name.

  7. At the top of the screen, select the check box for Apply New Style to Document Selection. With this setting on, the new class you’re about to create is applied to the <p> tag that you have selected.

  8. From the font-style drop-down list, choose italic. Your New Style dialog box should now look like Figure 3-18.

  9. Finally, click OK. Note that the entire paragraph is now displayed with an italic font.

    Beginning ASP.NET4 in C# and Visual Basic

    Figure 3-18

  10. With the <p> tag still selected, open the CSS Properties Grid (see Figure 3-19) by choosing View | CSS Properties. This grid gives you an overview of all the CSS properties and shows which ones are currently active for your page.

    Beginning ASP.NET4 in C# and Visual Basic

    Figure 3-19

    This grid shows a list of applied rules in the top half of the window. The bottom half of the window is used to show the CSS properties for those rules. In Figure 3-19 you see the rules that are applicable to the .Introduction selector. Properties that appear in blue and bold have their value set, whereas others appear in a normal font. If you don’t see these styles, click the third button on the toolbar of the CSS Properties Grid, which moves the properties that are set up in the list.

  11. In the CSS Properties list in the bottom half, locate the color property and set it to a dark blue color, like #003399. To achieve this, open the drop-down list for the property value and choose a color from the color picker. If the color you’re looking for is not available, click the More Colors button to bring up the extended color picker, shown in Figure 3-20.

    Beginning ASP.NET4 in C# and Visual Basic

    Figure 3-20

    Instead of using the color picker, you can also type in a value in the Properties Grid directly. This is how all properties work in the CSS Properties Grid: they let you enter values directly or enable you to visually change the value using a drop-down list or a button with ellipses at the end of the property’s value box. Figure 3-21 shows the different options you have for the font-style property in a convenient drop-down list.

    Beginning ASP.NET4 in C# and Visual Basic

    Figure 3-21

    Take special note of the three buttons at the top of the window, because they house some useful functionality. The first two buttons enable you to switch between categorized mode and alphabetical mode, making it easier to find the right property. The third button enables you to display the applied properties at the top of the list (as is the case in Figure 3-21) or at their default location in the list.

  12. Finally, save all changes and open Default.aspx in your browser (see Figure 3-22). You’ll see that the first paragraph is now displayed with a blue and italic font except for the link in the text, which should be green. Additionally, if you followed all the instructions from the previous chapter, the text “paying a visit” is red, set by the embedded CSS class.

    Beginning ASP.NET4 in C# and Visual Basic

    Figure 3-22

  13. Switch back to VWD and look at your page in Markup View. In the <head> section of the page, you should see the following embedded style sheet:

        .Introduction
        {
          font-style: italic;
          color: #003399;
        }
      </style>
      <link href=”Styles/Styles.css” rel=”stylesheet” type=”text/css” />
    </head>
    

The numerous tools that VWD offers make it easy to write CSS for your web site. You don’t need to hand code anything, or remember all the different properties that the CSS standard supports. Instead, you can simply choose them from different lists on the CSS Properties Grid. This grid enables you to enter values manually but also offers handy tools to select colors, files, and items from drop-down lists.

All changes you make in the Properties Grid are applied to the relevant style sheet, whether you’re working with an inline, embedded, or external style sheet. At the same time, the Design View is updated to reflect the new CSS options you have set.

When you look at the <h1> element, you can see that VWD created an inline style with a padding set to 0px to affect all four sides at once and a margin set to 0px 0px 10px 0px to control all four sides individually.

Once you have created a bunch of useful and reusable styles, you need a way to apply your existing styles to other pages or HTML elements. You see how this works next.

Applying Styles

If you have some experience with Microsoft Word, you may be familiar with the Styles dialog box, which lists all available styles and enables you to apply them to selected portions of text. This way, you can quickly apply identical formatting to blocks of text. This works similarly in VWD. With the Apply Styles window — accessible by choosing View | Apply Styles from the main menu — you can easily apply style rules to elements in the page.

In this exercise, you reuse the .Introduction class and apply it to the second paragraph of the page as well. That way, both paragraphs end up looking the same.

  1. Still in Default.aspx, make sure you’re in Design View and then select the second paragraph of the page by clicking it. Ensure that the Tag Selector at the bottom of the Document Window shows that the <p> tag is selected, and not another tag like <strong> that may be part of the <p> element. If you have only one paragraph of text, create a new one first (by pressing Enter after the first paragraph in Design View), enter some text, and then select that paragraph.

  2. Open the Apply Styles window by choosing View | Apply Styles. This window shows all the selectors it finds in the current page and any attached style sheet. If you don’t see all the styles shown in Figure 3-23, click the Options button and choose Show All Styles.

    Beginning ASP.NET4 in C# and Visual Basic

    Figure 3-23

    To help you find the right style, VWD uses a number of different visual cues. First of all, the Apply Styles window uses red, green, blue, and yellow dots to represent ID selectors, class selectors, element selectors, and inline styles, respectively. Figure 3-23 only shows red and green dots (you’ll just have to trust me) because the <p> element doesn’t have any inline styles applied. However, if you select the <h1> element, an inline style and an element selector appear. If you do try this out, make sure you select the <p> element again afterward. Furthermore, styles that are currently used in the page are surrounded by an additional circle, as is the case with all selectors in Figure 3-23.

  3. Click the Introduction class in the CSS Styles list. VWD adds a class attribute to the <p> tag:

    <p class=”Introduction”>
      Feel free to have a <a href=”Default.aspx”>look around</a>; there are lots of
      interesting <strong>reviews and concert pictures</strong> to be found here.
    </p>
    

    If you want to apply multiple classes, hold down the Ctrl key while clicking one of the other classes in the list. This applies a list of classes separated by a space to the element’s class attribute. You can follow the same steps to apply the selected style in Markup View as well.

  4. Using the Clear Styles button, you can quickly remove existing classes and inline styles from a tag. Consider the HTML fragment you saw in the previous chapter when you used the Formatting toolbar to format text in the page. If you used the Foreground Color button, you ended up with code similar to this:

    We&#39;re glad you&#39;re <span class=”style1”>paying a visit</span>
    

    To remove the class attribute, select the <span> tag in the tag selector, or simply click the <span> tag in Markup View and then click Clear Styles in the Apply Styles window, which you can see at the top of Figure 3-23. You’ll end up with this HTML:

    We&#39;re glad you&#39;re paying a visit
    

    Because an empty <span> around the text has no use, VWD removes it for you as well.

    Removing style attributes from HTML elements works the same way.

Once again, VWD is able to keep all relevant windows in sync: the Design View, Markup View, and the various CSS design tools. When you apply a class from the Apply Styles window, VWD adds the requested class to the selected HTML element in Markup View. It then also updates the Design View window. Similarly, when you remove a selector or a declaration from an embedded style in Design View, both the Design View and the CSS Tools windows are updated.

The final CSS functionality you need to look at in this chapter is located on the Manage Styles and Apply Styles windows. Besides helping you attach CSS files to your documents, these windows enable you to easily manage your styles.

Managing Styles

Because it’s so easy to add new inline and embedded styles, your pages may quickly become a mess with styles all over the place. To achieve reusability, you should move as much of your inline and embedded styles as possible to an external style sheet. This is exactly what the Apply Styles and Manage Styles windows enable you to do.

Earlier in this chapter, you modified the <h1> element and applied padding and margin to the heading. However, Default.aspx is not the only page that could benefit from this style for a heading, so it makes sense to move it to the Styles.css file. Similarly, the Introduction class seems reusable enough to include it in the Styles.css file so other pages can access it. This Try It Out shows you how to move styles around in your site.

  1. Make sure that Default.aspx is still open and switch to Markup View if necessary.

  2. Locate the <h1> element and click it once. VWD highlights the tag in the Tag Selector at the bottom of the Document Window to indicate it’s the active tag, as shown in Figure 3-24.

    Beginning ASP.NET4 in C# and Visual Basic

    Figure 3-24

  3. Open the Apply Styles window by choosing View | Apply Styles from the main menu. Alternatively, if you have the window docked with other windows, simply click its tab to make it active. Make sure the window is not accidentally docked in the main Document Window, but either floats or is placed at the side of the Document Window. At the bottom of the Apply Styles window, you’ll see an inline style appear (see Figure 3-25).

    Beginning ASP.NET4 in C# and Visual Basic

    Figure 3-25

  4. Right-click Inline Style and choose New Style Copy. The New Style dialog box appears, enabling you to create a new style based on the current selection. At the top of the window, choose h1 from the Selector drop-down list, and from the Define In drop-down list choose Existing style sheet. From the URL drop-down list, choose Styles/Styles.css. If that item isn’t available, click the Browse button to locate and select it. Your dialog box should end up like Figure 3-26.

    Beginning ASP.NET4 in C# and Visual Basic

    Figure 3-26

  5. Click OK to close the dialog box. VWD creates a copy of the h1 style and places it in the Styles.css file. Notice that VWD creates a new selector for h1 in the Styles.css file instead of adding the padding and margin info to the existing rule set. If you want, you could combine the two selectors into one manually.

  6. In the Apply Styles window, right-click Inline Style again, and this time choose Remove Inline Style from the context menu. This removes the style attribute from the h1 element.

  7. Switch to the Manage Styles window. Again, make sure the window is placed besides the Document Window and not docked in the Document Window. Under the Current Page item, locate the .Introduction selector, visible in Figure 3-27.

    Beginning ASP.NET4 in C# and Visual Basic

    Figure 3-27

  8. Click the .Introduction selector once, and then drag it into the area for Styles.css, for example dropping it after the h1 selector. Note that VWD draws lines between the selectors as you hover over them to indicate the point where the selector will end up. Figure 3-27 shows how the .Introduction selector is dragged from the current page into Styles.css, between the h1 and #PageWrapper selectors.

  9. Once you drop the selector in the Styles.css section of the Manage Styles window, the associated style is removed from your current page, and then inserted in Styles.css. Because that CSS file is included in your current page using the <link /> element, you won’t see a difference in Design View. You can now remove the empty <style> element from Default.aspx, because it’s not needed anymore.

  10. 10.Save any pending changes you may have and then open Default.aspx in your browser by pressing Ctrl+F5. Note that the paragraphs haven’t changed and still use the same blue and italic font.

Unfortunately, VWD doesn’t allow you to move inline styles to external style sheet files. However, by creating a copy of the existing style, and then deleting the original inline style, you can achieve the same effect. Moving embedded or external style sheets between files is a lot easier. You can simply drag a style from one file to another, and VWD will automatically move the code for you. This makes it extremely easy to organize your CSS. Instead of leaving all your embedded CSS in your page because you’re afraid to touch it, you can now simply drag and drop it into an external file. This makes it a lot easier to reuse those styles in other pages, decreasing page size and page bloat, and making your site a lot easier to manage. Obviously, it’s important that the file you are moving your CSS to is attached to the pages you’re working with.

Practical Tips on Working with CSS

Follow these tips to make the most of CSS:

  • Take some time to familiarize yourself with the many properties that CSS supports. The best way to do this is to create a brand new page in your Demos folder, create a few HTML elements like <div> and <p> tags, and then simply experiment with all the different properties. By trying out many of the properties on the CSS Properties Grid, you get a feel for what options you have available. This makes it easier later if you want to apply a certain effect to some piece of content.

  • When creating custom CSS classes, try to come up with names that describe the behavior of the rule, rather than the look and feel. For example, a class called .Introduction to style the first paragraph of a page is a good description. It enables you to change the underlying values without affecting the actual meaning of the name. But classes with names like .BlueAndItalic are guaranteed to give you problems later. What if you decide to change the blue to black later? You either end up with a very odd class name not describing its own behavior, or you’ll need to rename the class and then update the entire site, changing references to the old class to .BlackAndItalic.

  • Try to create smaller and reusable rule sets that you can combine if required, rather than creating large, monolithic rules that can only be used on a single UI element. For example, instead of creating a style like this:

    .ImportantHeading
    {
      font-size: 20px;
      font-weight: bold;
      color: red;
    }
    

    You’re better off creating a few lightweight rules that are easier to reuse:

    h1
    {
      font-size: 20px;
    }
    
    .Attention
    {
      font-weight: bold;
      color: red;
    }
    

    When you apply the .Attention class to a heading like this: <h1 class=”Attention”> you get the exact same behavior you got when you gave it the ImportantHeading class. However, with the separate Attention class, you have created a reusable rule that you can apply to other elements that need the user’s attention, like <p> or <span> elements.

Summary

This chapter gave you a good look at CSS, the most important language for styling your ASPX and HTML web pages.

CSS enables you to overcome the limitations of HTML with respect to styling your web pages because it is designed to minimize page bloat, give you greater control over the looks of your page, and generally help you create web sites that load quicker and that are easier to maintain.

Once you have a good understanding of the CSS terminology, you’ll find it’s easy to work with the many CSS tools that VWD has on board. Tools like the Manage Styles and Apply Styles windows, the Style Builder, and the smart IntelliSense in the code editor make writing and managing CSS very easy.

CSS can be applied not only to HTML as you’ve seen in this chapter, but also to ASP.NET Server Controls. The CSS you apply to those controls eventually ends up in the browser as plain HTML where the same principles apply as those you’ve seen in this chapter. The next chapter gives you a detailed look at the many available ASP.NET Server Controls.

Exercises

  1. What is the main benefit of using an external style over embedded style sheets?

  2. Write a CSS rule that changes the appearance of all headings at level one (h1) in your page to the following:

    • The heading uses an Arial font face.

    • The heading should be blue.

    • The heading must have a font size of 18 pixels.

    • The heading has a blue, thin border at the top and left sides.

  3. For the last requirement, check out VWD’s IntelliSense list in a CSS file to discover another shorthand version for the border property.

  4. Which of the two following rules is easier to reuse across pages in your web site? Can you explain why?

    #MainContent
    {
      border: 1px solid blue;
    }
    
    .BoxWithBorders
    {
      border: 1px solid blue;
    }
    
  5. VWD enables you to attach an external style sheet to a page in a number of different ways. Can you name three different options to do this?

Answers to Exercises can be found in Appendix A.

What You Learned in this Chapter

CSS

Cascading Style Sheets: the language to layout web pages in the browser

CSS Box Model

The model on which the dimensions of elements are calculated with regard to height, width, padding, border, and margin

Declaration

A combination of a property and a value that determines the styling for the element to which the declaration applies

Embedded style sheets

CSS code that is defined in a page in a <style /> element

External style sheets

CSS code that is defined in a separate file and then included in a page using the <link /> element

In-line style sheets

CSS defined directly on an element using the style attribute

Rule set

A combination of a selector and one or more declarations wrapped in a pair of curly braces

Selector

A CSS construct to point to one or more elements in the page. Different selectors exist, including the universal selector, the ID and class selectors and the element selector

Beginning ASP.NE T 4: in C# and VB, Copyright © 2010 by Wiley Publishing, Inc., ISBN: 978-0-470-50221-1, Published by Wiley Publishing, Inc., All Rights Reserved. Wrox, the Wrox logo, Wrox Programmer to Programmer, and related trade dress are trademarks or registered trademarks of John Wiley & Sons, Inc and/or its affiliates.