Style Basics for Your Web Site

Scott Allen | November 20, 2009

If you work in Web development, you should understand and use cascading style sheets (CSS). Effective use of CSS makes your applications more flexible, accessible, and consistent. CSS can remove redundancies in your code and make an application easier to maintain. It doesn’t matter if you are an ASP.NET Web Forms developer, an ASP.NET MVC developer, a PHP developer, or a technology-agnostic designer—there is no reason not to be using CSS these days. Every little bit you learn about style sheets pays dividends down the road.

This article is the first in a series in which I’ll examine cascading style sheets and drill into specific areas that are important for Web development. In this article, I’ll demonstrate how to write CSS rules and use CSS selectors. These basics are crucial to controlling the presentation of HTML and XHTML documents. In future articles, I’ll talk about layout, positioning, the CSS “box model,” typography, and more.

Presenting with Inline Styles

When you think about client-side programming, you usually assume that any code will run faster, appear seamless, and produce zero flickering. This is all true, but there’s another, equally important aspect to consider.

<ul>
    <li>Home</li>
    <li>Contact</li>
    <li>About</li>
</ul>

The content includes some markup and text. You can think of the markup as instructions telling the browser what to display. However, there isn’t any information in the markup telling the browser how to display the content. For example, there is nothing to tell the Web browser which font to use when it displays the text “Home,” or what color it should use to display the text. There isn’t any information telling the browser how to align the text or how large the text should appear relative to other text in the content. The browser will display the content using defaults for all these settings, so what you might see is shown in Figure 1.

If you want more control over how the browser presents the content, you can add inline style information in the markup, like this:

<ul style="font-size:larger; color:red">
    <li>Home</li>
    <li>Contact</li>
    <li>About</li>
</ul>

Style information includes a semicolon-delimited list of property names and their associated values. There are a wide range of properties you can set—everything from azimuth to z-index. A full list of standard CSS properties is available from the W3C at w3.org/TR/2009/CR-CSS2-20090423/propidx.html. The inline style used here on the ul tag tells the browser to display all text inside the ul using the color red and to use a larger size font than the default font. Figure 2 shows the results.

This is just a sample of how styles can control the presentation of content. In addition to colors, sizes, borders, and alignment, you can also influence where a particular piece of content appears on a page (using either absolute or relative positioning). I’ll return to the topic of positioning in a later article.

Although these inline styles, also known as local styles, are effective at controlling the presentation of content, they do face some serious drawbacks.

  • A local style can influence only a single element (and its children). If you have other content you want to display in red with a larger font, you need to duplicate the style in multiple places.
  • We’ve blended what to display with how to display it. This might sound like a trivial thing to worry about in such a simple example, but as your content and presentation rules become more complex, the result becomes a terrifying mixture of styles and content. When you want to modify the content you have to ignore all the presentation rules to find the content you need to modify. When you want to modify the presentation, you have to worry about not changing the content. It’s better to keep these concerns separate so that you can properly focus on each at the appropriate time.

Local styles rarely provide a long-term benefit to Web applications. Fortunately, there are better alternatives.

Embedded Styles

A slightly better approach to specifying presentation rules is to embed the information inside a style tag. The style tag belongs inside the head section of a Web page, as shown here:

<head runat="server">
  <title>basic css</title>
  <style type="text/css">  
    
      .special 
      {
          font-size:larger;
          color:red;
      }

  </style>
</head>

Inside the style tag is a CSS rule that includes a selector followed by a declaration wrapped in curly braces ({ and }). The declaration contains the same property names and values used in the inline styles example earlier. The browser uses the selector to select the elements that use this style rule. In this example, the selector tells the Web browser to apply this style rule to any element in the page with a class of “special”. It is the dot (.) before the word “special” that tells the browser this is a class name. With the rule in effect, you can easily make large, red text appear throughout a page.

<p class="special">Welcome!</p>
   <!-- .. other stuff .. -->
<ul class="special">
    <li>Home</li>
    <li>Contact</li>
    <li>About</li>
</ul>

Embedded styles are more effective than inline styles at separating content from presentation, but they still face some limitations in real-world Web applications.

  • Embedded styles are available only on a single page, meaning you can’t use the style consistently across multiple pages in an application.
  • Embedded styles add to the download size of a page. For dynamic pages where content changes but styles are static, embedded styles are overhead that could have been cached.

Embedded styles and inline styles work well only in trivial Web applications. For real applications, you want to share and enforce styles across multiple pages to achieve a consistent presentation style.

Linked Styles

Linked styles allow you to place style rules in a separate file—a style sheet with the extension .css. You can link to the style sheet and include it in one or more Web pages. Placing style rules in a separate file allows you to reuse style rules across multiple pages in a Web application, and even across multiple applications. Since the pages themselves no longer contain embedded and inline styles, their size is smaller. Browsers can cache the CSS files, yielding an even bigger savings in bandwidth and accelerating loading times for your web pages.

When you use external CSS files, style rules look the same as they do when they are embedded, as you can see here:

.special 
{
    font-size:larger;
    color:red;
}

If the previous rule is in a file named StyleSheet.css, you can include it in a Web page using a link tag in the head area of the page:

<head runat="server">
    <title>basic css</title>
    <link href="StyleSheet.css" rel="stylesheet" type="text/css" />
</head>

You can include as many style sheets in a single Web page as you want, and you can still use embedded and local styles on a page, even when the page links to a style sheet. Of course, this begs the question of how the browser behaves when rules from different sources appear to conflict with each other. I’ll answer this question later in the article. For now, let’s talk about rule declarations.

Declarations and Property Values

Rule declarations in CSS are the piece of the rule surrounded by curly braces. I’ve been using two declarations in the first rule example—one to control font size and one to control color. Each declaration ends with a semicolon.

.special 
{
    font-size:larger; /* declaration 1 */
    color:red;        /* declaration 2 */
}

Notice that style sheets can also include comments. Comments begin with /*, end with */, and can span multiple lines.

Each individual declaration in the preceding rule consists of the property name you want to affect and the value to give to the property. These parts of the rule are separated by a colon. The values you can specify for each property vary widely and can be one of the more confusing aspects of using CSS. You need to read the CSS specifications to find the legal values for each property or use a tool like Microsoft Visual Studio to edit your CSS files. Visual Studio can provide prompts and IntelliSense to guide you toward using a legitimate property value.

As an example, legal values for the color property include both keywords and numerical values. Keywords include the well-known CSS colors, like red, purple, white, black, lime, blue, and—my favorite—fuchsia. However, you can pick any color you like by using a numerical value in hexadecimal notation. Hexadecimal numbers begin with a # sign. Here’s an example:

.special 
{
    font-size:larger; 
    color: #ff0000;
}

The value #ff0000 specifies an RGB value where the red part of the color is completely on and the green and blue portions of the color are completely off. The legal range for each color component is from 0 to 255 (where 255 is equal to FF in hex). If you don’t like to use hexadecimal notation, you can also specify colors by using a functional notation. In this notation, as shown in the following example, style rules look like you are passing each color component as a parameter to an rgb function.

.special 
{
    font-size:larger; 
    color: rgb(255,0,0);
}

The font-size property is even more flexible. First, you can use the keywords larger and smaller to change the font size of an element relative to its parent’s font size. But you can also specify an absolute size using one of the following keywords:

  • xx-small
  • x-small
  • small
  • medium
  • large
  • x-large
  • xx-large

In addition to keywords, you can use numerical values to specify absolute or relative sizes. This is true for almost any “size” property that you specify in CSS. It doesn’t matter whether the “size” is the width of a border, the height of a div, or the size of a font. Anytime you specify a size numerically, you specify the unit of measurement from one of the following:

  • centimeters (cm)
  • inches (in)
  • millimeters (mm)
  • picas (pc)
  • pixels (px)
  • points (pt)

For example, to specify the font size as 15 millimeters, you could use the following rule:

.special 
{
    font-size:15mm; 
    color: red;
}

It’s quite common to specify the size of fixed-size elements, like img elements, using pixels (px). For font size, however, a best practice is to use only relative units. I’ll tell you why in just a bit. For relative units, you can choose between the following three options:

  • Em (em)
  • Ex (ex)
  • Percentage (%)

A percentage value looks like what you might expect. The following font-size declaration tells the browser to use a font size 200 percent larger than the current effective size:

.special 
{
    font-size:200%; 
    color: red;
}

The em unit is a unit of measurement for typography, so it is common to see relative font sizes specified in ems. You’ll also see padding and margin sizes specified in ems. A value of 1.0 is the default font size for an element, so a value of 1.2 ems would render a font 20 percent larger than the default.

.special 
{
    font-size:1.2em; 
    color: red;
}

As I mentioned earlier, it’s generally a good idea to specify relative sizes when it comes to fonts. The primary benefit is that you focus on the relationships between different pieces of content. For example, you might want paragraph text to be 0.8em versus 1.4em for a level-one heading. All these sizes will be relative to the default size. If you want to increase the size of all the content on a page, you can style the body tag with a larger font size (1.2em, for example). Since all the other sizes are specified using relative values, they also increase in size without you going back and setting absolute values.

Another primary benefit to using relative sizes is accessibility. A user who has a difficult time reading text on a computer display might increase the default size of all text (using View -> Text Size in Internet Explorer, for example). Specifying an absolute size overrides the user’s preference for text size and could make your page inaccessible.

Selectors

Selectors are the first part of each style rule. They tell the browser where to apply the style. The simplest selectors are the ones that specify which HTML tag name to style. The following rule applies to all h1 tags:

h1 
{
   background-color: green;    
}

You saw earlier how you can place multiple declarations in a single rule. You can also specify multiple selectors for a single rule by separating the selectors with a comma.

h1, h2, h3
{
   background-color: green;    
}

It’s also possible to have multiple rules apply to the same selector. For any given element in the browser, all the applicable rules combine to set the element’s properties (a topic I’ll expand on in the next section). For example, after the browser applies the following rules, an h2 element should appear with white text on a green background.

h1, h2, h3
{
   background-color: green;    
}

h1 { color: red; } 
h2 { color: white; }

A descendant selector allows you to target tags in a specific hierarchy for styling. For example, if you want to target p tags, but only p tags that exist somewhere inside a div tag, you can use the following rule:

div p 
{
    font-size: 0.8em;
}

A space between the first and second tag means the second tag can be located anywhere as a descendant of the first tag (as a child, a grandchild, a great grandchild, and so on). Use the > character to specify that the second tag should be a direct child, or the + symbol to indicate that the second tag should be a sibling of the first. The following rule targets only em tags that are direct children of a p tag.

p > em
{
    font-size: 1.1em;
}

You could continue to combine the selector syntax to target only em tags that are direct children of a p tag that are descendants of a div tag:

div p > em
{
    font-size: 1.6em;
}

The preceding rule would style the text Hello in the following HTML but not the words World or Goodbye:

<body>
    <div>
        <p>        
            <em>Hello</em>
            World!
        </p>
    </div>
    <p>
        <em>Goodbye</em>
    </p>
</body>

Tags, Classes, IDs

So far you’ve seen selectors being used with tags and classes, as here:

.special 
{
    font-size:1.2em; 
    color: red;
}

h1, h2, h3
{
   background-color: Green;    
}

Selectors based on tags are great for targeting content inside a specific document structure, while classes give you the freedom to target a specific piece of content regardless of where it appears in a document. You can combine the two if you want to write a style rule that targets specific tags using specific class values. The following targets only ul content with a class of special.

ul.special 
{
    font-size:1.2em; 
    color: red;
}

It’s also popular to style content based on an element’s ID attribute. While class selectors use a . (period), ID selectors use a # (hash).

#menu 
{
  text-align:center;   
}

Since an ID is allowed to appear only once in an XHTML document, use IDs to target unique pieces of content, like the navigation menu, header section, or footer section of a page. Use classes to style special pieces of content that might reappear throughout a page, like input fields that fail validation. Use a combination of selectors with descendants to avoid creating special classes everywhere. Keeping your CSS clean, simple, and easy to maintain is just as important as keeping the rest of your application code clean and simple.

Pseudo-Classes

Another type of selector commonly used in CSS is the pseudo-class selector. Pseudo-classes are not class names that appear in the page’s markup but are based on information that the browser can deduce about an element. For example, the :first-child pseudo-class, shown in the following, targets the first child element of some other element:

div:first-child 
{
    text-align:center;
}

The preceding rule would cause only the text Hello to center itself in the following content.

<div>
    <p>Hello</p>
    <p>World!</p>
</div>

It’s common to see selectors that use the link, visited, hover, and active pseudo-classes to style hyperlinks:

a:link { color:black; }
a:visited { color:gray; }
a:hover { text-decoration:none; }

Most browsers already display a visited link differently from an unvisited link, but you can use the pseudo-classes listed previously for more control. Other popular pseudo-classes include hover (when the user hovers over an element), active (when the user is clicking on an element), and focus (when an element has focus and is ready to accept keyboard input).

Cascading and Inheritance

Earlier, I talked about “defaults” in a browser, like the default font size. Where do these defaults come from? And what happens when style rules collide? The answers to these questions are some of the most important concepts in CSS.

Let’s start with the concept of inheritance. Just like children can inherit money from their parents, child elements can inherit default property values from their parent elements. The topmost parent in any HTML document is the body element. If you apply a style rule to the body element and no other style rules are in effect, all the body’s descendants inherit its property values. As an example, consider the following style rule:

body 
{
    font-size:1.0em;
    color:green;
}

With no other style rules in effect, all the text on the page with this rule is green—because the children of the body element inherit a green color setting, and their children, and their children, and so on. It’s important to understand, however, that not all property values are inherited. The CSS specification I pointed to earlier identifies which properties use inheritance. Most of the text attributes, like font size and color, use inheritance. However, many of the properties for positioning, like borders, margins, and padding, do not use inheritance. I’ll talk about these properties in a later article about CSS positioning.

The second important CSS concept to understand is cascading. The cascade feature is powerful and is the reason this technology is referred to as “cascading” style sheets. To understand how cascading works, you need to understand all the possible sources for style rules.

First, there is a “default” style sheet in every browser. In some browsers this default style sheet exists on the file system, but in many browsers the defaults are not easily accessible. (Internet Explorer stores some defaults in the Windows registry.) These defaults define the property values for HTML elements when no other style rules are in effect. Most browsers also allow for a user-defined style sheet. This is a style sheet a user creates and registers with a browser to apply the user’s own style rules to every site he or she visits. Many users do this for accessibility reasons—for example, to make the text larger on every site they visit.

On any given page, then, you can have style rules from the default style sheet, style rules from a user’s style sheet, and style rules from your own (the author’s) style sheets, as well as embedded and inline styles. The browser looks at styles in the following order:

  1. Default browser style sheet
  2. User style sheet
  3. Linked style sheets
  4. Embedded styles
  5. Inline styles

The general rule of thumb is that the later a style rule is declared, the higher precedence the rule has. Thus, a style rule defined as an embedded style can effectively override a style rule defined in an external style sheet.

Let’s take a step back and look at an example using inheritance and cascading. Imagine you have the following rules in an external style sheet:

p
{
    color: red;
}

body 
{
    font-size:1.0em;
    color:green;
}

Now imagine that you link to the style sheet in a page with the following HTML.

<body>      
    <h1>Welcome!</h1>
    <p>Hello !</p>       
</body>

In this scenario, the Welcome! text is displayed with the color green because it inherits a color setting from its parent’s body element. The Hello! text, however, is targeted with the color red, and it is displayed in red.

Now imagine that you embed the following style rule.

<style>
    p 
    {
        color: black;
    }
</style>

Now the Hello! text is displayed in black because the embedded style rule effectively overrides the style rule for p elements defined in the external style sheet. Although the cascading behavior of style rules is a little more complicated than what I describe here, this should be enough to get you started, and I hope you can recognize what a powerful feature it is.

Conclusion

This article should give you everything you need to get started with CSS. You now know how to use selectors and declarations and have a basic understanding of inheritance and the cascade behavior. To see the bigger picture is to see how CSS can help you build more maintainable applications by separating your content from your presentation rules. By keeping your rules in an external CSS file, you can easily modify the look and the presentation of an application by changing a few style rules instead of crawling through your pages and content making changes. In the end, your customers and users will benefit from your increased productivity and knowledge of CSS.

 

About the Author

Scott Allen is the Principal Consultant and a founder of OdeToCode LLC, and also a member of the Pluralsight technical staff. Scott has more than 16 years of commercial software development experience with a wide range of technologies. He's delivered products on embedded, Windows, and web platforms. Scott  writes the Extreme ASP.NET column for MSDN Magazine and is a featured speaker at conferences and workshops around the world.

Find Scott on: