Print this Section

  
  

Style Selectors and Classes

Use of embedded style sheets has been suggested as the normal way to apply page-wide styles to tags. Where particular tags need to take on special styles different from these page-wide styles, in-line style sheets are used to modify the styling.

Where practical, embedded style sheets should always be the preferred styling method, even for application of special one-time-only styling. Embedded style sheets localize style settings within the single <style> section of the page, thereby making them more accessible than if scattered across multiple in-line style sheets. Also, embedded style sheets can be easily promoted to linked style sheets for site-wide application. Discussed below are ways to apply special styling to page elements by using embedded style declarations rather than in-line style sheets.

Simple Selectors

By way of review, most embedded styling can be done with individual tag selectors and their associated style declarations. These simple selectors declare default tag styling for an entire page. The general format for a simple selector is shown in Listing 3-38.

selector {property:value [; property:value] ... }

Listing 3-38. General embedded style sheet format for a simple selector.

Any number of selectors can be combined with any number of style properties within an embedded style sheet. For example, the following simple selectors set page-wide formatting for page margins, headings, and paragraphs. Anywhere one of these tags is encountered on the page, the browser applies the associated style.

    <style> 
        body       {margin:20px; color:black;}
        h1         {color:blue; text-align:center;}
        h2         {color:blue; text-align:left;}
        p          {text-align:justify; text-indent:25px;}
    </style> 

Listing 3-39. An embedded style sheet applying simple selectors.

There will likely to be occasions where these page-wide styles need to be modified for particular tags. For example, one or more of the paragraphs in the document may require different alignment or indention, or a particular heading may use a different style to emphasize it differently from other headings. Although you can use in-line style sheets to override these embedded style declarations, there are ways to designate exceptional styling within the embedded style sheet itself.

ID Selectors

One way to apply special styles to individual page elements is to provide the element with a unique identifier. After which, special styling can be applied only to the element with that identifier that is within the embedded style sheet.

For instance, assume that common paragraph indention and alignment are adopted for an entire Web page with the embedded style sheet declaration shown above. That is, all paragraphs have 25-pixel indentions and are text justified with first-line indents of 25 pixels. Now assume that one particular paragraph on the page requires different styling. This single paragraph needs to be offset from surrounding paragraphs with 25-pixel left and right margins and it should not have first-line indention.

The first step in styling this particular paragraph is to assign it an id value. An id is a unique identifier for the tag. It can be any name you choose using combinations of alphabetic and numeric characters. In the following code, id="Special" is assigned to the paragraph requiring special formatting.

    <p id="Special">This paragraph requires special styling different from regular
    paragraphs on the page. It should be offset 25 pixels from both margins and not 
    have first-line indention.</p> 

Listing 3-40. Identifying a paragraph for application of special styling.

With an id assigned to this <p> tag it can be designated for special styling by using an ID selector in the embedded style sheet. The general format for an ID selector is shown in Listing 3-41.

#id{property:value [; property:value]...}

Listing 3-41. General style sheet format for ID selector.

Styling is applied to the element on the page that contains an id="value" property, where "value" matches the #id name. Thus, an ID selector can be added to the above style sheet to format the special paragraph differently from regular paragraphs:

    <style>
      body       {margin:20px; color:black;}
      h1         {color:blue; text-align:center;}
      h2         {color:blue; text-align:left;}
      p          {text-align:justify; text-indent:25px;}
      #Special  {text-indent:0px; margin-left:25px; margin-right:25px;}
    </style>

Listing 3-42. Applying styling to an ID selector.

The syntax #Special refers to the tag with the id value (#) of "Special". The standard 25-pixel first-line indention given by the p simple selector is reset to 0 pixels for this particular paragraph. Also, the paragraph is given left and right margin settings different from normal paragraphs. Nevertheless, its text remains justified as inherited from standard paragraph styling given through the p selector. In other words, all paragraphs inherit the styling given by the p simple selector unless these styles are modified or supplemented by an #id selector.

ID Selectors can be used for identifying and styling any HTML tag. Just assign a unique id="value" attribute to the tag and add the ID Selector #value to the stylesheet. ID Selectors should be unique and assigned to only one tag in the HTML document. In this way, the id property in tags serve to uniquely identify them for specific reference in stylesheets.

Styling Spans and Divisions

You should not style <span> or <div> tags with simple selectors in an embedded style sheet. These tags often appear multiple times on a page to isolate and style different portions of text and different collections of page elements, all of which usually require a different styling. Thus, you cannot associate one particular style with these tags without reducing their flexibility in styling other spanned text or divisions that require a different styling. In other words, do not code the following simple selectors in embedded style sheets.

<style>
  div     {property:value}
  span    {property:value}
</style>

Listing 3-43. Avoid using simple selectors for <div> and <span> tags.

However, by using ID selectors you can apply different styles to different <span> and <div> tags without committing them to one particular style.

In the following example, two paragraphs are given the same style by enclosing them inside a <div> to which special styling is applied. The style effects only this single division through its unique ID selector. Styling of other divisions is not affected since they do not have this id value. At the same time, two <span> tags take on their unique stylings through their unique id values, and leave any other stylings of spanned text unaffected.

    <style>
        #Justify   {text-align:justify;}
        #Red   {color:red;}
        #Blue    {color:blue;}
    </style>
    
    <div id="Justify">
        <p>This paragraph is styled by inheriting the styling of its container
        division which is formatted with the <span  id="Red">"Justify"</span>style.</p>

        <p>This paragraph is also styled by inheriting the styling of its container
        division. In addition, <span id="Blue">BLUE</span> styling is applied to
        one of its words.</p> 
    </div> 

Listing 3-44. Using ID selectors for styling individual <div>and <span> tags.

Style Classes

By defining a class selector a general-purpose style can be declared for broad application to any tags needing to share the style. A class selector is defined in an embedded style sheet as shown by its general format in Listing 3-45.

.class {property:value [ ;property:value] ...}

Listing 3-45. General style sheet format for class selector.

Rather than naming a tag or using an id as the selector, a class name is supplied, preceded by a period. This .class selector can be a name of your choosing, but cannot include spaces or special characters. Any combination of style properties and values can be associated with this style class.

The following embedded style sheet includes a style class named .Offset. Once this class has been defined, it is assigned to any tag with the class="class" attribute. Below, the style class is applied to a paragraph by assigning it to the <p> tag. This paragraph takes on the styling of the .Offset class, in this case overriding normal styling given by the p simple selector.

<style>
  p       {margin:20px;}
  .Offset {margin-left:30px; margin-right:30px;}
</style>

<p  class="Offset">This paragraph requires special styling different from normal
paragraphs on the page. It has left and right margins of 30 pixels.</p>

Listing 3-46. Declaring and applying a style class.

(Note that the class assigned in the tag does not include the period that is necessary when declaring the .class selector in the style sheet.)

A style class is a general-purpose style that can be applied to any type of tag simply by assigning the class to the tag. Furthermore, unlike the ID selector, the class selector can be assigned to any number of tags. Thus, any paragraphs, divisions, or other block-level tag types can reflect the above styling by assigning them to the .Offset class. Of course, the tag to which the class is applied must be receptive to the particular properties and values declared for the class.

Style classes are particularly relevant to <span> and <div> tags for styling text strings and blocks of code without committing these tags to one particular style. The tags become carriers for many different styles simply by assigning different style classes to them. The following code is an example of applying various style classes through various tags to produce the page display shown in Figure 3-27.

    <head>
      <title>Class Styles</title>

    <style>
      .Offset  {margin-left:25px; margin-right:25px; text-align:justify;}
      .Red     {color:red;}
      .Blue    {color:blue;}
      .Rule    {height:2px; width:75%; text-align:center; color:green;}
    </style>

    </head>
    <body>

    <hr class="Rule">

    <div class="Offset">

      <p>Here is a paragraph that takes on the formatting given for its enclosing 
      division. Within this paragraph the word <span class="Red">RED</span> has its 
      own style class applied.</p>
	
      <p>This paragraph also is styled by its enclosing division. Within this 
      paragraph the word <span class="Blue">BLUE</span> has its own style class
      applied.</p>

    </div>

    <hr class="Rule" >

    </body>

Listing 3-47. Declaring and applying various style classes.

Class Styles examle

Figure 3-27. Application of class styles.


Both of the above paragraphs are styled by enclosing them inside a division to which the .Offset style class is assigned. Thus, the paragraphs inherit division styling. In this case, both paragraphs are offset from the page margins and the text is justified. This technique has the same effect as declaring an ID selector for division styling (div#Offset) and applying the style through this ID selector (<div id="Offset">). However, the .Offset class is more flexible since it can be associated with other multiple tags. Any tags on the page can take on the .Offset style by assigning them to this class.

Within each paragraph are individual words that take on color styling. These words are enclosed inside <span> tags through which colors are applied by assigning the tags to either the .Blue or .Orange style class. Incidentally, if any other sections of the page — a paragraph, a heading, whatever — need to be displayed in one of these colors, then their enclosing tags can be assigned these same style classes. Any normal stylings of these tags are supplemented with assigned colors.

Both horizontal rules are 75% of the width of the page, 2 pixels in height, green, and centered. The choice is made to define a style class to represent this styling and to assign all <hr> tags to this class. Of course, these styles could be defined for the simple hr selector without using a class; however, the choice is made to create classes for all stylings and to assign tags to these classes according to what is required. It would not be unusual to find an embedded style sheet composed exclusively of style classes that are selectively applied to all varieties of tags requiring those styles.

CSS Media Types

CSS Media Types allow you to specify how documents will be presented in different media such as the browser screen, on paper, hand held devices, and other types of common media. The ability to control page layout in different types of media can be helpful because a document usually needs a larger font-size on a screen than on paper; and sans-serif fonts are easier to read on the screen, while serif fonts are easier to read on paper. Among other things, CSS Media Types also allow you to customize your page for various types of accessibility devices. Guidelines for creating accessible sites will be discussed later in another tutorial.

The table below lists the different CSS Media Types and describes how they are used.

Media Type Description
all Used for all media type devices.
braille Used for braille tactile feedback devices.
embossed Used for printing on braille printers.
handheld Used for small handheld devices.
print Used for printers.
projection Used for projected presentations, like slides.
screen Used for computer screen
speech Used for speech and sound synthesizers.
tty Used for terminals or devices with limited display capabilities.
tv Used for televisions.

Figure 3-28. Table of CSS Media Types.

The @media media type { } rule allows different style rules for different media in the same style sheet.

    <head>
      <title>Class Styles</title>

    <style>
    @media screen {
      p {font-size:11pt;font-family:Arial;}
    }

    @media print {
      p {font-size:10pt;font-family:Times New Roman;}
    }
    </style>

    </head>
    <body>

    <p>This example tells the browser to display a 
    11 point Arial font on the screen, but if the page is 
    printed, it will be in a 10 point Times New Roman font. 
    </p>

    </body>

Listing 3-48. Declaring and applying styles for different media types.

When the page is viewed in the browser, the text is rendered in 11 point Arial. When the page is printed, the font size is 10 points and in Times New Roman.

Styling Strategies

By now, you are probably confused. You have a choice of using linked style sheets, embedded style sheets, in-line style sheets, or some combination of the three. When using linked or embedded style sheets you have a choice of using simple tag selectors, ID selectors, or style classes. Later in this tutorial, additional styling options are presented. What's a person to do about all these options?

Given the various approaches to styling, a reasonable strategy to follow is outlined below. You may developed your own preferred approach as you become more familiar with style sheets, but the following outline is a good beginning to sort out the options.

  • Use an embedded style sheet as the primary styling method. This permits isolation of styles within a single section of the page thereby making it easier to locate and change styles. It also promotes embedded styles to a linked style sheet for site-wide application.
  • Within the embedded style sheet, use simple tag selectors to apply common, page-wide styling to all tags of the same type.
  • Define style classes to apply styling through general-purpose tags such as <span> and <div> tags. Also, use style classes when two or more tags require formatting different from or supplementary to that given by their simple tag selectors.
  • For single tags requiring unique styling, assign an id value to the tag and apply its styling through an ID selector in the embedded style sheet.
  • Use an in-line style sheet where one-time styling is required and there is overriding convenience in having the style sheet coded inside the tag. Too many in-line style sheets are difficult to track down for changes; plus, identical in-line styles have to be changed in multiple locations, leading to possible oversight and errors.

Although preference is given to using embedded style sheets -- and by extension, linked style sheets the -- these tutorials often use in-line style sheets as instructional devices to introduce and describe style properties. The assumption is, however, that in-line styles will be elevated to embedded or linked styles when pages are "put into production."

This tutorial has given you a first introduction to style sheets. There are many more style properties to come and many other variations on those introduced here. The importance of style sheets cannot be over-emphasized. With deprecation of most tag formatting attributes, style sheets have become the primary technique for arranging and displaying page content. The use of in-line, embedded, and linked style sheets has become the essence of HTML5 coding.


TOP | NEXT: Chapter 4 - Text Formatting