Jump to content

User:Moncur/12

Ka Wiktionary

<!- -

12. Working with Style Sheets

[wax ka badal]

Style and Substance

[wax ka badal]

If you've ever tried to make a really good-looking web page, you've probably encountered some problems. First of all, HTML doesn't give you very much control over a page's appearance. For example, you can't change the amount of space between words—in fact, you can't even use two spaces between words because they'll be converted to a single space.

Second, even when you do your best to make a perfect-looking document using HTML, you will find that it doesn't necessarily display the same way on all browsers—or even on different computers running the same browser.

The reason for these problems is simple: HTML was never meant to handle such things as layout, justification, and spacing. HTML deals with a document's structure—in other words, how the document is divided into paragraphs, headings, lists, and other elements.

This isn't a bad thing. In fact, it's one of the most powerful features of HTML. You only define the structure of the document, so it can be displayed in all sorts of different ways without changing its meaning. For example, a well-written HTML document can be displayed in Netscape, Firefox, or Internet Explorer, which generally treat elements the same way—there is a space between paragraphs, headings are in big, bold text, and so on.

Because HTML only defines the structure, the same document can be displayed in a text-based browser, such as Lynx. In this case, the different elements will be displayed differently, but you can still tell which text is a heading, which is a list, and so on.

By the Way
Text-based browsers aren't the only alternative way of displaying HTML. Browsers designed for the blind can read a web page using a speech synthesizer, with different voices or sounds that indicate the different elements.

As you should now understand, HTML is very good at its job—defining a document's structure. Not surprisingly, using this language to try to control the document's presentation will only drive you crazy.

Fortunately, the World Wide Web Consortium (W3C) realized that web authors need to control the layout and presentation of documents. This resulted in the Cascading Style Sheets (CSS) standard.

CSS adds a number of features to standard HTML to control style and appearance. More importantly, it does this without affecting HTML's capability to describe document structures. Although style sheets still won't make your document look 100% identical on all browsers and all platforms, it is certainly a step in the right direction.

Let's look at a real-world example. If you're browsing the Web with a CSS-supported browser and come across a page that uses CSS, you'll see the document exactly as it was intended. You can also turn off your browser's support for style sheets if you'd rather view all the pages in the same consistent way.

Did you Know?
Using CSS and simplifying HTML markup is also helpful in making pages compatible with the various tiny browsers used on mobile phones.

Defining and Using CSS Styles

[wax ka badal]

You can define a CSS style sheet within an HTML document using the <style> tag. The opening <style> tag specifies the type of style sheet—CSS is currently the only valid type—and begins a list of styles to apply to the document. The </style> tag ends the style sheet. Here's a simple example:

<style type="text/css">
H1 {color: blue;}
</style>

Because the style sheet definition itself doesn't create any output on the page, you should place the <style> tags in the <head> section of the HTML document.

Watch Out!
You can only use style sheet rules within the <style> tags. HTML tags are not valid within a style sheet.

Creating Rules

[wax ka badal]

Each element within the <style> tags is called a rule. To create a rule, you specify the HTML elements that it will affect, as well as a list of properties and values that control the appearance of those elements. We'll look at the properties in the next section.

As a simple example, the following style sheet contains a single rule. All Level 1 headings are blue:

<style type="text/css">
H1 {color: blue;}
</style>

Each rule includes three components:

  • A selector (H1 in the example) describing which HTML tags will be affected
  • One or more property names (color in the example)
  • A value for each property name (blue in the example)

Each rule uses braces to surround the list of properties and values, and a semicolon after each value. The semicolon is optional if you are only specifying one property and value.

You can specify multiple HTML tags for the selector, as well as multiple properties and values. For example, the following style sheet specifies that all headings are blue, italic, and centered:

<style type="text/css">
H1,H2,H3,H4,H5,H6 {color: blue;
font-style: italic;
text-align: center; }
</style>
By the Way
If you make a rule that sets the style of the <body> tag, it will affect the entire document. This becomes the default rule for the document, but you can override it with the styles of elements within the body of the page.

Setting Styles for Specific Elements

[wax ka badal]

Rather than setting the style for all elements of a certain type, you can specify a style for an individual element only. For example, the following HTML tag represents a Level 1 heading colored red:

<h1 style="color: red; text-align: center;">This is a red heading.</h1>

This is called an inline style because it's specified in the HTML tag itself. You don't need to use <style> tags with this type of style. If you have used both, inline style rules override rules in a style sheet—for example, if the preceding tag appeared in a document that sets H1 headings to be blue in a style sheet, the heading would still be red.

Using id Attributes

[wax ka badal]

You can also create a rule within a style sheet that will only apply to a certain element. The id attribute of an HTML tag enables you to assign a unique identifier to that element. For example, this tag defines a paragraph with the id attribute intro:

<p id="intro">This is a paragraph</p>

After you've assigned this attribute to the tag, you can include rules for it as part of a style sheet. CSS uses the pound sign (#) to indicate that a rule applies to a specific id. For example, the following style sheet sets the intro paragraph to be red in color:

<style type="text/css">

# intro {color: red;}

</style>
Watch Out!
An id value should define a single element in a page. Most browsers will enable you to define more than one element with the same id value, but this is not valid and will not work consistently. It's best to use classes, as described in the next section, when you need to apply the same styles to multiple elements.

Using Classes

[wax ka badal]

Although the id attribute is useful, you can only use each unique id value with a single HTML tag. If you need to apply the same style to several tags, you can use the class attribute instead. For example, this HTML tag defines a paragraph in a class called smallprint:

<p class="smallprint">This is the small print</p>

To refer to a class within a style sheet, you use a period followed by the class name. Here is a style sheet that defines styles for the smallprint class:

<style type="text/css">
.smallprint {color: black;
font-size: 10px; }
</style>
By the Way
You can use a class on any number of elements within a page. You can also define multiple classes for an element, separated by spaces: class="smallprint bold". When you do this, the CSS rules for all of the classes will be applied to the element.

Using CSS Properties

[wax ka badal]

CSS supports a wide variety of properties, such as color and text-align, in the previous example. The following sections list some of the most useful CSS properties for aligning text, changing colors, working with fonts, and setting margins and borders.

Did you Know?
This is only an introduction to CSS, and there are many properties beyond those listed here. For more details about CSS, consult one of the web resources or books listed in [Appendix A], "Other JavaScript Resources."

Aligning Text

[wax ka badal]

One of the most useful features of style sheets is the capability to change the spacing and alignment of text. Most of these features aren't available using standard HTML. You can use the following properties to change the alignment and spacing of text:

  • letter-spacing Specifies the spacing between letters.
  • text-decoration Enables you to create lines over, under, or through the text, or to choose blinking text. The value can be none (default), underline, overline, line-through, or blink. Blinking text is, thankfully, unsupported by most browsers.
  • vertical-align Enables you to move the element up or down to align with other elements on the same line. The value can be baseline, sub, super, top, text-top, middle, text-bottom, and bottom.
  • text-align Specifies the justification of text. This can be left, right, center, or justify.
  • text-transform Changes the capitalization of text. capitalize makes the first letter of each word uppercase; uppercase makes all letters uppercase; and lowercase makes all letters lowercase.
  • text-indent Enables you to specify the amount of indentation for paragraphs and other elements.
  • line-height Enables you to specify the distance between the top of one line of text and the top of the next.

Changing Colors and Background Images

[wax ka badal]

You can also use style sheets to gain more control over the colors and background images used on your web page. CSS includes the following properties for this purpose:

  • color Specifies the color of the text within an element. This is useful for emphasizing text or for using a specific color scheme for the document. You can specify a named color (for example, red) or red, green, and blue values to define a specific color (for example, #0522A5).
  • background-color Specifies the background color of an element. By setting this value, you can make paragraphs, table cells, and other elements with unique background colors. As with color, you can specify a color name or numeric color.
  • background-image Specifies the URL for an image to be used as the background for the element. This is specified with the keyword url and a URL in parentheses, as in url(/back.gif).
  • background-repeat Specifies whether the background image is repeated (tiled). The image can be repeated horizontally, vertically, or both.
  • background-attachment Controls whether the background image scrolls when you scroll through the document. fixed means that the background image stays still while the document scrolls; scroll means the image scrolls with the document (like background images on normal web documents).
  • background-position Enables you to offset the position of the background image.
  • background Provides a quick way to set all of the background elements in this list. You can specify all of the attributes in a single background rule.
Did you Know?
The basic list of colors supported by most browsers for the color and background-color properties includes aqua, black, blue, fuchsia, gray, green, lime, maroon, navy, olive, orange, purple, red, silver, teal, white, and yellow.

Working with Fonts

[wax ka badal]

Style sheets also enable you to control the fonts used on the web document and how they are displayed. You can use the following properties to control fonts:

  • font-family Specifies the name of a font, such as arial or helvetica, to use with the element. Because not all users have the same fonts installed, you can list several fonts. The CSS specification also supports several generic font families that are guaranteed to be available: serif, sans-serif, cursive, fantasy, and monospace.
  • font-style Specifies the style of a font, such as normal, italic, or oblique.
  • font-variant This value is normal for normal text, and small-caps to display lowercase letters as small capitals.
  • font-weight Enables you to specify the weight of text: normal or bold. You can also specify a numeric font weight for a specific amount of boldness.
  • font-size The point size of the font.
  • font This is a quick way to set all the font properties in this list. You can list all the values in a single font rule.

Margins and Borders

[wax ka badal]

Last but not least, you can use style sheets to control the general layout of the page. The following properties affect margins, borders, and the width and height of elements on the web page:

  • margin-top, margin-bottom, margin-left, margin-right Specify the margins of the element. You can specify the margins as an exact number or as a percentage of the page's width.
  • margin Allows you to specify a single value for all four of the margins.
  • width Specifies the width of an element, such as an image.
  • height Specifies the height of an element.
  • float Enables the text to flow around an element. This is particularly useful with images or tables.
  • clear Specifies that the text should stop flowing around a floating image.
Did you Know?
Along with these features, CSS style sheets enable you to create sections of the document that can be positioned independently. This feature is described in [Hour 13], "Using the W3C DOM."

Units for Style Sheets

[wax ka badal]

Style sheet properties support a wide variety of units, or types of values you can specify. Most properties that accept a numeric value support the following types of units:

  • px Pixels (for example, 15px). Pixels are the smallest addressable units on a computer screen or other device. In some devices with non-typical resolutions (for example, handheld computers) the browser might rescale this value to fit the device.
  • pt Points (for example, 10pt). Points are a standard unit for font size. The size of text of a specified point size varies depending on the monitor resolution. Points are equal to 1/72 of an inch.
  • ex Approximate height of the letter x in the current font (for example, 1.2ex).
  • em Approximate width of the letter m in the current font (for example, 1.5em). This is usually equal to the font-size property for the current element.
  • % Percentage of the containing object's value (for example, 150%).

Which unit you choose to use is generally a matter of convenience. Point sizes are commonly used for fonts, pixel units for the size and position of layers or other objects, and so on.


Creating a Simple Style Sheet

[wax ka badal]

As an example of CSS, you can now create a web page that uses a wide variety of styles:

  • For the entire body, the text is blue.
  • Paragraphs are centered and have a wide margin on either side.
  • Level 1, 2, and 3 headings are red.
  • Bullet lists are boldface and green by default.

The following is the CSS style sheet to define these properties, using the <style> tags:

<style type="text/css">
BODY {color: blue}
P {text-align: center;
margin-left:20%;
margin-right:20%}
H1, H2, H3 {color: red}
UL {color: green;
font-weight: bold}
</style>

Here's a rundown of how this style sheet works:

  • The <style> tags enclose the style sheet.
  • The BODY section sets the page body's default text color to blue.
  • The P section defines the style for paragraphs.
  • The H1, H2, H3 section defines the style for heading tags.
  • The UL section defines a style for bullet lists.

To show how this style sheet works, [Listing 12.1] shows a document that includes this style sheet and a few examples of overriding styles for particular elements. [Figure 12.1] shows Internet Explorer's display of this example.

Listing 12.1. An Example of a Document Using CSS Style Sheets
<html>
<head><title>Style Sheet Example</title>
<style type="text/css">
BODY {color: blue}
P {text-align: center;
margin-left:20%;
margin-right:20%}
H1, H2, H3 {color: red}
UL {color: green;
font-weight: bold}
</style>
</head>
<body>
<h1>Welcome to this page</h1>
<p>The above heading is red, since we specified that H1-H3 headings
are red. This paragraph is blue, which is the default color for
the entire body. It's also centered and has 20% margins, which we
specified as the default for paragraphs.
</p>
<p style="color:black">This paragraph has black text, because it overrides
the default color in the paragraph tag. We didn't override the centering,
so this paragraph is also centered.</p>
<ul>
<li>This is a bullet list.
<li>It's green and bold, because we specified those defaults for bullet lists.
<li style="color:red">This item is red, overriding the default.
<li>This item is back to normal.
</ul>
<p>This is another paragraph with the default paragraph style.</p>
</body>
</html>
Did you Know?
Remember that you can download the code for this listing from this book's website.

Using External Style Sheets

[wax ka badal]

The preceding example only changes a few aspects of the HTML document's appearance, but it adds about 10 lines to its length. If you were trying to make a very stylish page and had defined new styles for all of the attributes, you would end up with a very long and complicated document.

For this reason, you can use a CSS style sheet from a separate file in your document. This makes your document short and to the point. More importantly, it enables you to define a single style sheet and use it to control the appearance of all of the pages on your site.

Linking to External Style Sheets

[wax ka badal]

You can refer to an external CSS file by using the <link> tag in the <head> section of one or more HTML documents:

<link rel="stylesheet" type="text/css" href="style.css">

This tag refers to an external CSS style sheet stored in the style.css file.

By the Way
Using external style sheets is a good practice because it separates content (HTML), presentation (CSS), and behavior (JavaScript). See [Hour 15], "Unobtrusive Scripting," for more information on best practices.

Creating External .css Files

[wax ka badal]

After you've linked to an external .css file, you need to create the file itself. The external style sheet is a simple text file that you can create with the same editor you use for HTML documents.

The .css file should contain a list of CSS rules, in the same format you would use between <style> tags. However, the file should not include <style> tags or any other HTML tags. Here is what the styles from the previous example would look like as an external style sheet:

BODY {color: blue}
P {text-align: center;
margin-left:20%;
margin-right:20%}
H1, H2, H3 {color: red}
UL {color: green;
font-weight: bold}

Controlling Styles with JavaScript

[wax ka badal]

The new W3C DOM (Document Object Model) makes it easy for JavaScript applications to control the styles on a page. Whether or not you use style sheets, you can use JavaScript to modify the style of any element on a page.

As you learned in [Hour 4], "Working with the Document Object Model (DOM)," the DOM enables you to access the entire HTML document and all of its elements as scriptable objects. You can change any object's style by modifying its style object properties.

The names and values of objects under the style object are the same as you've learned in this hour. For example, you can change an element's color by modifying its style.color attribute:

element.style.color="blue";

Here, element represents the object for an element. There are many ways of finding an element's corresponding object, which you will learn about in detail in [Hour 13].

In the meantime, an easy way to find an element's object is to assign an identifier to it with the id attribute. The following statement creates an <h1> element with the identifier "head1":

<h1 id = "head1">This is a heading</h1>

Now that you've assigned an identifier, you can use the getElementById() method to find the DOM object for the element:

element = document.getElementById("head1");

You can also use a shortcut to set styles and avoid the use of a variable by directly working with the getElementbyId() method:

document.getElementById("head1").style.color="blue";

This statement combines the preceding examples by directly assigning the blue color style to the head1 element of the page. You'll use this technique to create a dynamic page in the following Try It Yourself section.

Try It Yourself — Creating Dynamic Styles

[wax ka badal]

Using the DOM style objects, you can create a page that enables you to directly control the colors used in the page's text. To begin with, you will need a form with which to select colors. You can use <select> tags to allow a color choice:

<select name="heading" onChange="changehead();">
<option value="black">Black</option>
<option value="red">Red</option>
<option value="blue">Blue</option>
<option value="green">Green</option>
<option value="yellow">Yellow</option>
</select>
By the Way
If you are unsure of the syntax used in forms, you might want to review [Hour 11], "Getting Data with Forms."

Notice that this <select> definition uses onChange attributes in the <select> tags to call two functions, changehead() and changebody(), when their respective selection changes.

Combining two of these selections with some basic HTML results in the complete HTML document shown in [Listing 12.2].

Listing 12.2. The HTML File for the Dynamic Styles Example
<html>
<head>
<title>Controlling Styles with JavaScript</title>
<script language="Javascript" type="text/javascript"
src="styles.js">
</script>
</head>
<body>
<h1 id="head1">
Controlling Styles with JavaScript</h1>
<hr>
<p id="p1">
Select the color for paragraphs and headings using the form below.
The colors you specified will be dynamically changed in this document.
The change occurs as soon as you change the value of either of the
drop-down lists in the form.
</p>
<form name="form1">
<b>Heading color: </b>
<select name="heading" onChange="changehead();">
<option value="black">Black</option>
<option value="red">Red</option>
<option value="blue">Blue</option>
<option value="green">Green</option>
<option value="yellow">Yellow</option>
</select>
<br>
<b>Body text color: </b>
<select name="body" onChange="changebody();">
<option value="black">Black</option>
<option value="red">Red</option>
<option value="blue">Blue</option>
<option value="green">Green</option>
<option value="yellow">Yellow</option>
</select>
</form>
</body>
</html>

Notice that the <h1> tag has an id attribute of "head1", and the <p> tag has an id of "p1". These are the values the script will use in the getElementById() function. The <script> tag in the <head> section links the document to the styles.js script, which you will create next.

Save your HTML file as styles.html. You can test it in a browser now, but the dynamic features will not work until you create the JavaScript file containing the script functions. [Listing 12.3] shows the JavaScript code for this example.

Listing 12.3. The JavaScript File for the Dynamic Styles Example
function changehead() {
i = document.form1.heading.selectedIndex;
headcolor = document.form1.heading.options[i].value;
document.getElementById("head1").style.color = headcolor;
}
function changebody() {
i = document.form1.body.selectedIndex;
doccolor = document.form1.body.options[i].value;
document.getElementById("p1").style.color = doccolor;
}

This script first defines the changehead() function. This reads the index for the currently selected heading color, and then reads the color value for the index. This function uses the getElementById() method described in the previous section to change the color. The changebody() function uses the same syntax to change the body color.

Store your JavaScript file as styles.js, and be sure it is in the same folder as the HTML document you saved from [Listing 12.2].

To test the dynamic styles script, load [Listing 12.2] (styles.html) into the browser. Select the colors, and notice the immediate change in the heading or body of the page. [Figure 12.2] shows a typical display of this document after the colors have been changed.

Summary

[wax ka badal]

In this hour, you've used style sheets to control the appearance of web documents. You've learned the CSS syntax for creating style sheets, and used JavaScript to control the styles of a document.

In the next hour, you will move on to Dynamic HTML (DHTML) using layers and other features of the W3C DOM.

Q1: What's the difference between changing the appearance of text with traditional tags, such as <b> and <i>, and using a style sheet?


A1: Functionally, there is no difference. In principle, though, the HTML should define the structure of the document, and CSS should define the presentation.


Q2: What happens if two style sheets affect the same text?


A2: The CSS specification is designed to allow style sheets to overlap, or cascade. Thus, you can specify a style for the body of the document and override it for specific elements, such as headings and paragraphs. You can even go one step further and override the style for one particular instance of an element. CSS has a set of rules governing which styles have precedence over others, although you might find that different browsers interpret CSS differently when you have many overlapping styles.


Q3: With CSS in one separate file and JavaScript in another, doesn't web development get confusing?


A3: Yes, this can make a simple page unnecessarily complex. However, as you build more complex pages, you'll find it very helpful to have three separate files. This lets you deal with the content and structure (HTML), presentation (CSS), and behavior (JavaScript) separately.

Q4: What if users don't like the styles I use in my pages?

A4: This is another distinct advantage style sheets have over browser-specific tags. With the latest browsers, users can choose a default style sheet of their own and override any properties they want.

Quiz Questions

[wax ka badal]

Test your knowledge of style sheets and JavaScript by answering the following questions.

1. Which of the following tags is the correct way to begin a CSS style sheet?

  1. <style>
  2. <style type="text/css">
  3. <style rel="css">

2. Why isn't the normal HTML language very good at defining layout and presentation?

  1. Because it was designed by programmers.
  2. Because magazines feared the competition.
  3. Because its main purpose is to define document structure.

3. Which feature of new browsers allows you to use JavaScript statements to change styles?

  1. HTML 4.0
  2. The DOM
  3. CSS 2.0

Quiz Answers

[wax ka badal]

1. b. You begin a CSS style sheet with the tag <style type="text/css">.

2. c. HTML is primarily intended to describe the structure of documents.

3. b. The DOM (Document Object Model) enables you to change styles using JavaScript.

Exercises

[wax ka badal]

If you want to gain more experience using CSS style sheets, try the following exercise:

  • Modify [Listing 12.2] to include an <h2> tag with a subheading. Add a form element to select this tag's color, and a corresponding changeh2 function in the script.
  • Now that [Listing 12.2] has three different changeable elements, there is quite a bit of repetition in the script. Create a single ChangeColor function that takes a parameter for the element to change, and modify the onChange event handlers to send the appropriate element id value as a parameter to this function.