Web Development Tutorials




  
  

Applying Styles

A large part of HTML5 coding involves the application of styling characteristics to page elements. Styling includes the positioning of elements on the page along with such visual appearances as font faces, sizes, colors, and other display characteristics. There are two basic ways to control the layout and appearance of page elements: through tag attributes and through style sheets. These methods are described briefly here and are elaborated and illustrated throughout the tutorial.

Attributes

Formatting styles can be applied through attributes coded within HTML tags. Particular tags have particular attributes that are specific to them and that control the appearance of whatever page content they contain. As a quick example, a horizontal rule is displayed across the page wherever the <hr> tag is coded. This tag produces the following line that is often used to separate paragraph level content on page.


Figure 3-1.

Default horizontal rule.


The above line is the default display of the tag. It can take on a different appearance by coding attributes inside the tag. The size attribute controls the depth of the line; the width attribute gives its length; the color attribute sets its color, and the align attribute specifies its horizontal position on the line (to the left of the page, to the right of the page, or centered on the page).

Tag attributes are coded in the general format attribute="value". The attribute is named and a quoted value is supplied for its setting. Below is an <hr> tag coded with four attributes to control its displayed appearance as shown in Figure 3-2.


Figure 3-2.

Red horizontal rule 50% of the width of the Web page.


The line is 10 pixels in height (size="10"), 50% of the width of the browser window (width="50%"), red in color (color="red"), and centered horizontally on the page (align="center"). Thus, attribute values give styling characteristics to display the rule differently from its normal default style. As you proceed through this tutorial, particular attributes associated with particular tags are presented as styling options for those tags.

Under HTML5 standards, most of the styling attributes of tags have been deprecated. This means that the attributes are still recognized in modern browsers, but the recommendation is to abandon their use in favor of other styling methods. The movement is towards use of Cascading Style Sheets, rather than attributes, to apply styling to HTML5 elements.

Cascading Style Sheets

The preferred way to apply styling to page elements is with Cascading Style Sheets (CSS). A style sheet is a set of style properties and accompanying style values that describe the appearance of HTML5 elements to which they are applied. There are three methods of creating style sheets: an in-line style sheet appears inside the tag to which its style declarations apply; an embedded style sheet is a separate style section of a Web page which applies its styles to all designated tags on a page; and a linked style sheet is an external document containing style settings that apply to all pages that link to it.

In-line Style Sheets

in-line style sheet is coded inside a tag to apply styling to that particular tag. It is coded in the general format shown in Listing 3-1.

<tag style="property: value [; Property:value] ..."> </tag>

Listing 3-1. General format for an in-line style sheet.

One or more property:value pairs give style settings within a style attribute coded in the tag. Multiple style properties settings are separated from each other with semicolons, and spaces can be included between the settings to help with readability.

To some extent, the properties and values that can be coded for a tag depend on the particular tag being styled. For instance, style settings for a horizontal rule can include height, width, color, and text-align properties, identical in effect to the deprecated size, width, color, and align attributes they replace. These properties are coded as an in-line style sheet as shown in Figure 3-3. A style attribute appears inside the <hr> tag and specifies a set of properties and values to apply to the tag when it is displayed in the browser.

<hr style="height:10px; width:50%; color:red; text-align:center">

Listing 3-2. Horizontal rule created with an in-line style sheet.


Figure 3-3.

Horizontal rule created with an in-line style sheet.


When applied as in-line style sheets, the properties and values pertain only to the tag in which they are coded. This means that if there are several <hr> tags on a page, each would need to include the same in-line style sheet to share the same style. This may not present a problem with only a few tags; however, with many tags it can be tedious and error-prone to code the same style sheet in all of the individual tags. A way is needed to declare style settings one time and to share these settings among multiple tags.

Embedded Style Sheets

To avoid duplicate coding of in-line style sheets, an embedded style sheet can be used. An embedded style sheet is defined within a <style> tag, normally coded in the <head> section of the page. Within this <style> section is a list of tag names, called selectors, to which style declarations (properties and values) are assigned. Once these declarations are made, they are automatically applied to the identified tags wherever they are located on the page.

Older HTML languages required the additional <style> tag attribute type="text/css" to be included in order to specify the type of content surrounded by <style> tags; however, in HTML5 the type automatically defaults to "text/css" when omitted, making it unnecessary to include. The general format for the <style> section of a document is shown in Listing 3-3.

    <style>selector {Property:value [; Property:value] ...}
        ...   
    </style>

Listing 3-3. General format for embedded style sheet.

A selector is a tag name (without the enclosing < and > symbols). Style properties and values for the tag are enclosed within a list of style declarations, separated by semicolons, and all enclosed within a pair of braces { }. For example, the following code specifies style declarations for the <hr>tag by supplying the same style settings as in the previous in-line style sheet.

    <head>
        <title>Embedded Style Sheet Example</title>

        <style>
            hr { height:10px; width:50%; color:red; text-align:center; }
        </style>
    </head>

Listing 3-4. Application of an embedded style sheet.

The hr selector is associated with four property:value declarations to style a horizontal rule. Once these styles are defined within an embedded style sheet, they are applied automatically wherever the browser encounters an <hr> tag in the document. It is not necessary to code separate in-line style sheets within each and every <hr> tag. The tag itself carries the styling described in the embedded style sheet.

Although shown above with a single selector for the <hr> tag, an embedded style sheet can contain any number of entries depending on how many different tags are to be styled. The example is also coded on a single line. Many Web page authors prefer to code property:value settings on separate lines for ease of reading and editing as shown in Listing 3-5.

    <style>
          hr {
            height:10px;
            width:50%;
            color:red;
            text-align:center;
          }
    </style>

Listing 3-5. Alternate coding for an embedded style sheet.

The typed format of style sheet entries does not affect their styling. Like HTML code, style sheet code is in free format: it can be arranged in any fashion as long as the codes and punctuation are correct.

Whether to employ an embedded style sheet or multiple in-line style sheets is a matter of coding efficiencies and personal choice. Normally, if a style is applied to multiple occurrences of a tag it involves less coding and fewer errors to code an embedded style sheet by declaring the style one time for sharing by all designated tags. One the other hand, if a style is applied only once to a single tag, then there is convenience in coding an in-line style sheet for that one particular tag. Later, strategies are presented for dealing with various styling situations.

Linked Style Sheets

If your Web site contains multiple pages,then a third style sheet alternative is probably the best solution. It permits you to conveniently apply the same styles to all pages without having to duplicate in-line or embedded style sheets on each page.

A linked style sheet is a separate document containing property:value settings in the same format as an embedded style sheet. The only difference is that the linked document does not include <style> tags surrounding the entries. For example, a linked style sheet document containing specifications for the <hr> tag described above includes the entries shown in Listing 3-6.

    Stylesheet.css (document)

    hr {
        height:10px;
        width:50%;
        color:red;
        text-align:center
    } 

Listing 3-6. A linked style sheet document.

This separate document is created with a text editor and saved as a standard text file, usually with the file extension .css to identify it as a style sheet document. It is a common practice to save the document under the name Stylesheet.css in the same directory as the Web pages to which it applies.

A linked style sheet document contains style settings that are applicable to all pages of the Web site. Therefore, all pages that use the style sheet must "link" to it to make the styles available to those pages. This linkage occurs with a <link> tag coded in the <head> section of the page. The general format for the <link> tag is shown in Listing 3-7.

<link
  href="url"
  rel="stylesheet"
>

Listing 3-7. General format for <link> tag.

The href (hypertext reference) attribute gives the location of the linked style sheet. If the style sheet appears in the same directory as the Web page to which it applies, then this entry is simply the name of that document. The rel attribute specifies the relationship of the external document to the current page (always "stylesheet"). Just as with the <style> tag, the attribute type="text/css" historically was necessary to include in order to tell the browser what type of resources was being linked. Under HTML5, when the type tag is omitted, it automatically defaults to "text/css", making its inclusion unnecessary.

If you have a style sheet document named Stylesheet.css that is located in the same folder as your Web page. You link the Web page to this document using the following HTML code.

<head>
    <title>Linked Style Sheet Example<title>
    <link href="Stylesheet.css" rel="stylesheet">
</head>

Listing 3-8. Linking a Web page to a linked style sheet.

Now the Web page has available to it all of the style settings included in the Stylesheet.css document. This linked style sheet can serve to replace embedded or in-line style sheets that otherwise would appear on individual Web pages. As in the case with embedded style sheets, any tags identified with selectors in a linked style sheet carry with them the declared styles.

Style Sheet Comments

It is usually a good idea to place comments in your CSS document to describe its various sections. Comments are general descriptions or explanations of CSS code. These serve as useful reminders of the purposes or contents of sections of code when you or someone else returns at a later time to edit the document.

CSS comments are coded between a /* and */. Comments can span multiple lines. The example below demonstrates the use of CSS comments.

/* Set Page Font Family */

body {font-family:arial}

/* You can also comment an entire block during testing

.comment {font-weight:bold}

*/

Listing 3-9. Examples of comments that span multiple lines.

Besides their use for including comments in a CSS document, comment tags can be used to temporarily suspend browser display of a section of code. This purpose is often useful in "debugging" your page, that is, in trying to discover errors by selectively removing sections of code from display until the problem is isolated.

Applying Style Sheets

It would not be uncommon to employ all three types of style sheets for a single Web page. A linked style sheet would contain styles that are common to all Web pages; an embedded style sheet would contains styles that are pertinent to the particular page; and in-line style sheets would apply to individual tags for which common styling is not needed. The browser handles these multiple style sheets in the following fashion.

  • First, any linked style sheets are applied to the identified tag selectors on the page.
  • Second, any embedded style sheets are applied. If the same tag selectors appear in both the linked and embedded style sheets then embedded styles override or augment linked styles.
  • Third, any in-line style sheets are applied. If these settings pertain to the same tags that appear in either linked or embedded style sheets, then in-line styles override or augment both linked and embedded styles.
  • The general principle in force is that any lower-level style setting takes precedence over an equivalent higher-level style setting. In-line style sheets take precedence over embedded style sheets which, in turn, take precedence over linked style sheets.

Assume, for example, that a linked style sheet contains the following style declarations for horizontal rules.

hr {
        height:1px;
        width:50%;
        color:red;
        text-align:center;
    } 

Listing 3-10. Linked style sheet for horizontal rules.

All pages that link to this style sheet display horizontal rules in this style. Now assume that one particular page needs differently styled rules, say, ones that are blue rather than red. An embedded style sheet is coded on this single page in order to override the color declaration in the linked style sheet:

<style>
    hr {color:blue;}
</style>

Listing 3-11. Embedded style sheet for horizontal rules.

All horizontal rules on this page are blue; however, they retain the height, width, and text-align properties from the linked style sheet. Tags on this page inherit the properties of the linked style sheet unless modified by the embedded style sheet.

Assume further that one particular horizontal rule on this page needs to be green and extend to the width of the page. An in-line style sheet is added to this particular rule.

    <hr style="color:green; width:100%;">

Listing 3-12. In-line style sheet for a horizontal rule.

Green styling overrides the blue color that is inherited from the embedded style sheet, and a width of 100% overrides the 50% width inherited from the linked style sheet. This particular rule, however, retains its 1 pixel height and centered alignment inherited from the linked style sheet.

Style inheritance is what makes style sheets "cascading." Linked styles are inherited by, or cascade across, all Web pages that link to them; embedded styles are inherited by, or cascade across, an entire Web page containing a <style> section; and in-line styles are inherited by, or cascade across, individual tags containing in-line style sheets.

Throughout these tutorials, style properties and values are introduced and illustrated as in-line style sheets with discussion on how they can be elevated to embedded on linked style sheets for wider application. By the end, you should be at ease with style sheets and with the many ways they offer to design Web pages to meet your most exacting design requirements.

Validating CSS

The W3C maintains a free CSS Validation Service available at http://jigsaw.w3.org/css-validator that can be used to validate CSS code and check it for syntax errors. The CSS validation tool can help identify code that needs to be corrected quickly and indicate which style rules a browser likely to consider valid.

CSS Validator

Figure 3-4.

W3C CSS Validation Service.


There are three options for validating CSS.

  1. You can enter the URL for the external or linked .css file.
  2. You can upload a CSS file from your local PC.
  3. You can paste your CSS into a text box.

TOP | NEXT: Margin Styles