Chapter 3: Designing Your Web Pages

Applies to: Visual Studio 2010

Published: April, 2010

Provided by: Imar Spaanjaars

Book Cover

Buy This Book from Publisher

This topic contains the following sections.

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.

Although earlier versions of Visual Web Developer lacked good tools for working with CSS, the IDE of Visual Web Developer 2008 has great support for CSS and is able to render pages much closer to how they’ll eventually end up in the browser. The new tools enable you to visually create CSS, making it much easier to style your pages without the need to know or remember every little detail of CSS.

In this chapter, you’ll learn more about the following topics:

  • What CSS is and why you need it

  • What the CSS language looks like 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.

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

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 <b> 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 only offers a limited set of options to style your pages. You can use tags like <i>, <b>, 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 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 as the first paragraph in each of the pages in your web 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 all the additional markup in your page adds considerably to the size of the page. This makes it slower to download and display as the information needs to be downloaded with each page in your web site. It also makes it harder to maintain your pages as 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 allows 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 allowing 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, while the CSS file defines how you want to display it, enabling you to change or switch one of the two documents, leaving the other unmodified. You’ll see how this works in the next section. 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, as you can then no longer control style information from a single, central location.

Since 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’ll 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 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.

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. While 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 contained 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’ll 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.

Try it Out: Writing Your First CSS

In this Try It Out you’ll 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 that make writing CSS easy.

  1. In the Planet Wrox project, create a new file called CssDemo.aspx in the Demos folder. For this exercise, it doesn’t matter if you choose inline code or code behind. The programming language for the page doesn’t matter either, as you’ll only use the markup part of the page.

  2. Make sure the page is in Markup View and then locate the </head> tag in the source. Right before this tag, type the following highlighted code:

      <title>Untitled Page</title>
      <style type=”text/css”>
    
      </style>
    </head>
    
  3. Note that as soon as you type the opening angle bracket (<), a list pops up that allows 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.

  4. Next, between the opening and closing <style> tags, type the following highlighted 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, as 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.

  5. Scroll down in the page a little until you see the opening <div> tag. Right after this tag, type the following highlighted 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 type class=”RightAligned”, but in later exercises in this chapter you’ll see how you can have the IDE write this code for you.

  6. 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.

    Figure 3-1

    Referenced Screen

    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. Since CSS is case sensitive, there’s a difference between RightAligned and rightaligned.

    If you want to display the page in your browser, press Ctrl+F5. VWD spins up the built-in web server, then opens your default browser and sends it to the CssDemo.aspx page. 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) 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 there are many other selectors available, which you’ll see later in this section. Figure 3-2 shows how the elements are related to each other.

Figure 3-2

Referenced Screen

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.

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’ll 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, allowing you to group them under a single selector, like this:

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

This code 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 and understand, 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 a specific element within your page. A number of different selectors are available, giving you fine control over what element 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 allows you to point to a specific HTML element. 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> tags 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 allows you to refer to a single element in the page. Within an HTML or ASPX page, you can give each 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;
}

Since 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 more than once, 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.

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 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 as it allows 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 allows you to group multiple selectors, which 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, allowing 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:

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

This rule affects only paragraphs that fall within the MainContent element, leaving all other paragraphs unmodified.

Note that combining is very different from grouping. Grouping is just a shortcut to avoid typing the same declarations over and over again, while combining allows 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.Highlight
{
  font-size: 18px;
  font-weight: bold;
}

This rule changes all paragraphs with the class Highlight within an 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=”Highlight”>Because I have a class called Highlight, my text appears in bold</p>
  <p>This text is not bold, as it lacks the Highlight class</p>
</div>
<p class=”Highlight”>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, allowing you to hide or show them.

display: none;

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

float

float: left;

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 or not. 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.

NoteNote

There are many more properties available in CSS than I have described here. For more detail on CSS, get yourself a copy of Beginning CSS: Cascading Style Sheets for Web Design, Second Edition by Richard York (ISBN: 978-0-470-09697-0).

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 since you’re limited to a relatively short list of named colors, you often need the hexadecimal notation to get the exact color you want.

There are many other values 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 allow 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, like this:

  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, as 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 value in a CSS file or <style> block in VWD.

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

Try it Out: Styling the Planet Wrox Homepage

In this exercise you’ll modify two files: First, you’ll 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’ll modify the Styles.css file from the Styles folder to change the size and location of these elements. Finally, you’ll 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 in Markup View the file Default.aspx from the root of your web site.

  2. Right before the welcome text you created in the previous chapter, add the following highlighted HTML. Make sure you replace the existing HTML in the <form> element:

    <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”>
        </div>
        <div id=”Sidebar”>Sidebar Goes Here</div>
        <div id=”Footer”>Footer Goes Here</div>
      </div>
      <h1>Hi there visitor and welcome to Planet Wrox</h1>
      ...
    </form>
    

    This code uses <div> elements to identify important regions of the page, like the header, the menu, and the main content area.

  3. Select the headingand the paragraphs (represented by the ellipsis (...) in the code snippet from step 2) you added to this page earlier, cut them to the clipboard, and then paste them between the opening and closing tags of the MainContent<div>. This moves your existing code into the main content block. You should end up with something 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 code in the page looks like the code from step 2. It’s important that the various <div> elements and their IDs end up right, while the actual welcome text is less of a concern.

  4. Open the file Styles.css from the Styles folder. If you added some code to this file during an earlier Try It Out, remove that code first.

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

    #Header
    {
    
    }
    
  6. 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-3 appears.

  7. 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-4.

    Figure 3-3

    Referenced Screen

    Figure 3-4

    Referenced Screen

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

  8. Switch to the Position category by clicking it in the list on the left. The panel that appears allows 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 83. 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: 83px;
    }
    
  9. Repeat steps 5 through 8, this time creating the following rules:

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

    You find the float and clear properties in the layout category of the Modify Style dialog box.

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

  11. 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. VWD inserts code in the head section of the page in Markup View that attaches the style sheet to the document:

    <head runat=”server”>
      <title>Untitled Page</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.

  12. 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-5, which shows the page in Mozilla Firefox.

    Figure 3-5

    Referenced Screen

TipTip

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. Sometimes, when you need to make minor tweaks to your code, it’s 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: 644px; float: left; } #Sidebar { background-color: Gray; width: 200px; float: left; }

This tells the MainContent to “float” on the left side of the Sidebar, effectively placing the Sidebar to the right of it. 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’ll 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 folder Styles 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-5.

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

Adding CSS to Your Pages

The most useful way to add CSS styles to your web pages is through the <link> tag 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 allows 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 another way to include style sheets at the beginning of this chapter: using embedded <style> elements. The <style> tag 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 a <h1> element in the current page alone, you can add the following code to the <head> of your page:

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

The final way to apply CSS to your HTML elements is to use inline styles with the style attribute that you saw in the previous chapter. Since 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=”background-color: Black; color: White;”>
    This is white text on a black background
</span>

Choosing among External, Embedded, and Inline Style Sheets

Since you have so many options to add style sheets to your site, what’s the best method to use? In general, you should preference external style sheets over embedded styles, which in turn are preferred over inline styles. External style sheets allow 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 pick up the change automatically, instead of going through each page in your site and manually making the changes to embedded or inline style sheets.

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. This demonstrates the cascading part of cascading style sheets, where one style cascades down to the other. 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, as the setting in the external style sheet now overrules that of the embedded style.

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

NoteNote

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’ll learn how to do in the next section, which discusses the remainder of the CSS tools in VWD.

VWD has a number of handy tools on board for working with CSS. Most of them are new in the 2008 release of VWD, as good CSS support was one of the design goals of this latest release. The following tools are at your disposal:

  • 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 different 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.

Although you’ve already seen some of these tools in this chapter, the next sections give you a detailed look at the functionality they offer. You’ll see how to carry out tasks, like creating new styles, modifying existing ones, and applying styles to existing elements. During the explanation, you get a good look at the tools mentioned here.

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’ll see how to use the Add Style Rule window to create a new rule in an external file. You’ll then use the Style Builder to modify the rule.

Try it Out: Creating New Styles in an Existing Style Sheet

In this exercise, you’ll 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 then click the first button, labeled Add Style Rule, or choose Styles | Add Style Rule from the main menu. The dialog box shown in Figure 3-6 appears.

    Figure 3-6

    Referenced Screen

    With this dialog box you can visually create a combined selector. In the left section of the dialog box, you can enter Type, Class, and ID selectors.

    Select the last option, labeled Element ID, and then in its text box type MainContent. Click the button with the right arrow in the middle of the screen to add the selector to the Style rule hierarchy.

  4. Next, select the Element radio button at the top of the dialog box and then 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-7.

    Figure 3-7

    Referenced Screen

    If you don’t see the hash symbol (#) in front of MainContent in the Style rule hierarchy box, make sure you selected Element ID and not Element in step 3 of this exercise.

  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 dialog box, place a check mark for the underline option. The Style dialog box should now look like the one shown in Figure 3-8.

    Figure 3-8

    Referenced Screen
  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 then 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 style 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;
    }
    
TipTip

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 grouped 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 for 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’ll 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. There are a number of ways to do this, including typing in the code by hand or dropping the file in Markup or in Design View. The next Try It Out exercise shows you a third option: using the Manage Styles dialog box.

Try it Out: Attaching Your New Style Sheet to Your Document

In this exercise, you’ll remove and reattach the style sheet called Styles.css to your Default.aspx page so you’ll see another alternative to attaching a style sheet file to an ASPX page. You’ll 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-9 appears.

    Figure 3-9

    Referenced Screen

    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 the previous chapter.

  2. Click the Attach Style Sheet link in the Manage Styles window, 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:

      </style>
      <link href=”Styles/Styles.css” rel=”stylesheet” type=”text/css” />
    </head> 
    
  3. When you attach the style sheet, the Manage Styles window (shown in Figure 3-10) is updated and now shows your newly attached style sheet.

  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 the 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.

    Figure 3-10

    Referenced Screen
  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-11.

    Figure 3-11

    Referenced Screen
  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 probably 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, click the Delete History button. This clears your entire browsing history, so when you reload the page now 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 allows you to clear the history using the Tools | Clear Private Data 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 the page in VWD 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 ellipses 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.

TipTip

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’ll see how to do in the next section. When you opened 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.

Useful as external style sheets may be, there are times where 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, an embedded, or an 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 allows you to create styles at all three levels. Even better, it allows 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’ll see how to create inline and embedded style sheets. You’ll see later how to move those styles to an external style sheet, enabling other pages to reuse the same styles.

Try it Out: Creating Embedded and Inline Styles in a Page

In this Try It Out, you’ll 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’ll 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 to select it and then choose Format | New Style. The New Style dialog box appears (visible in Figure 3-12), which is pretty similar to the Modify Style dialog box you saw earlier.

    Figure 3-12

    Referenced Screen
  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-13.

    This dialog box has a handy diagram that shows you where CSS properties like padding, border, and margin end up. In the middle you see a blue rectangle that represents your element like <h1> or <body>. Around it, you see another rectangle that represents the padding. Around that, the border is applied. Finally, at the outer sides of the diagram you see margin that is applied outside the border of an element.

    Figure 3-13

    Referenced Screen

    By default, browsers draw some white space above or below an <h1> element. To give each browser the same 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> 
    

    Next, in Design View, click the first paragraph by clicking on it. A small glyph appears to indicate you selected a <p> element, as visible in Figure 3-14. Also make sure the Tag Selector at the bottom of the Document Window highlights the <p> element, and not something else.

    If you don’t see the glyph, you need to select Block Selection from the View | Visual Aids menu in VWD.

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

    Figure 3-14

    Referenced Screen

    Figure 3-15

    Referenced Screen
  6. 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.

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

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

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

    Figure 3-16

    Referenced Screen

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

  10. 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-17.

    Figure 3-17

    Referenced Screen

    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 allow you to visually change the value using an arrow or a button with ellipses at the end of the property’s value box. Figure 3-18 shows the different options you have for the font-style property in a convenient drop-down list.

    Figure 3-18

    Referenced Screen

    Take special note of the three buttons at the top of the window, as they house some useful functionality. The first two buttons allow 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 selected properties at the top of the list (as is the case in Figure 3-18) or at their default location in the list.

  11. Finally, save all changes and open Default.aspx in your browser (see Figure 3-19). 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.

    Figure 3-19

    Referenced Screen
  12. 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>
    
TipTip

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 allows 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’ll see how this works next.

Applying Styles

If you have some experience with Microsoft Word, you may be used to the Styles dialog box, which lists all available styles and allows 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 panel—accessible by choosing View | Apply Styles from the main menu—you can easily apply style rules to elements in the page.

Try it Out: Applying Styles

In this exercise, you’ll 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 <b> 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 dialog box 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-20, click the Options button and choose Show All Styles.

    Figure 3-20

    Referenced Screen

    To help you find the right style, VWD uses a number of different visual cues. First of all, the Apply Styles dialog box uses red, green, and yellow dots to represent ID selectors, class selectors, and inline styles respectively. Figure 3-20 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 appears. 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-20.

  3. Click the Introduction class in the dialog box, and VWD adds a class attribute to the <p> tag:

    <p class=”Introduction”>
      Feel free to have a <a href=”Default.aspx”>look around</a>; as there are lots of
      interesting <b>reviews and concert pictures</b> 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 are <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 dialog box, which you can see at the top of Figure 3-20. You’ll end up with this HTML:

    We&#39;re glad you are 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.

TipTip

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

Especially since it’s so easy to add new inline and embedded styles, your pages may quickly become messy. 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 allow you to do.

Try it Out: Managing Styles

Earlier in this chapter, you modified the <h1> element and applied padding and margins to the heading. However, Default.aspx is not the only page that could benefit from this style, 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> tag and click it once. VWD makes the tag bold to indicate it’s the active tag, as shown in Figure 3-21.

    Figure 3-21

    Referenced Screen
  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. At the bottom of the Apply Styles window, you’ll see an inline style appear (see Figure 3-22).

    Figure 3-22

    Referenced Screen
  4. Right-click Inline Style and choose New Style Copy. The New Style dialog box appears, allowing 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-23.

    Figure 3-23

    Referenced Screen
  5. Click OK to dismiss the dialog box. VWD creates a copy of the h1 style and places it in the file Styles.css. 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 selector. If you want, you could combine the two selectors into one manually.

  6. In the Apply Styles dialog box, 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. Close the Apply Styles dialog box and open the Manage Styles window. Under the Current Page item, locate the .Introduction selector, visible in Figure 3-24.

    Figure 3-24

    Referenced Screen
  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-24 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. Since that CSS file is included in your current page using the <link /> element, you won’t see a difference in Design View. You can remove the empty <style> tag from Default.aspx, as it’s not needed anymore.

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

TipTip

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.

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 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 allows 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;
}

h1

{
  font-size: 20px;
}

.Attention
{
  font-weight: bold;
  color: red;
}

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

CSS allows you to overcome the limitations of HTML with respect to styling your web pages as 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.

Due to its simple set of grammar rules, CSS is relatively easy to learn. There is some important terminology that you need to be aware of before you can start using the full potential of CSS. First, you have to understand what a rule set or a rule is. A rule is a combination of a selector and one or more declarations that define the look of elements on your page. The selector is used to point to one or more elements in your page; the declaration determines how that element should look. The declaration itself can be split in two parts: the property and the value. The property determines what part of the element selected by the selector must be styled, while the value determines how it ends up.

When you have a good understanding of the CSS terminology, you’ll find it’s easier to work with the many CSS tools that VWD has on board. Tools like the Manage Styles and Apply Styles window, the Style Builder, and the smart IntelliSense in the code editor make writing CSS a breeze. Instead of remembering every little detail about CSS, you can rely on the built-in tools to write proper CSS for you.

At the end of the chapter, you saw how to use the Manage Styles window to move rules from an ASPX page to an external style sheet. This is extremely useful if you want to keep your pages tidy. You can start off by adding embedded style sheets in the document directly. When you’re done with the page, you can move some or all of your rules to external style files, so that they can be used by the pages in your site as well. This dialog box is also useful if you want to reorder the different selectors in a single CSS file: You can just drag and drop them in a new location.

This chapter laid a good foundation for working with CSS in VWD 2008. The remainder of this book uses that knowledge to create good looking and well-organized web pages.

CSS can be applied not only to HTML as you’ve seen in this chapter, but to ASP.NET Server Controls as well. 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.

  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. Which of the two following rules is easier to reuse across pages in your web site? Can you explain why?

  4. #MainContent
    {
      border: 1px solid blue;
    }
    
    .BoxWithBorders
    {
      border: 1px solid blue;
    }
    
  5. VWD allows 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?

Beginning ASP.NET 3.5: In C# and VB, Copyright © 2008 by Wiley Publishing, Inc., ISBN: 978-0-470-18759-3, 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.

Show: