Computer Science Illuminated, Third Edition

eLearning

Animated Flashcards
Live Wire
Cryptic Crossword Puzzles
Ethical Issues
Biographical Sketches
Did You Know
Goin Live
Google Code Digital Lab Manual
Online Glossary
The Learning Store
Language Library
Download PEP/7
Instructor Resources
Student Resources

eLearning Home

Lab #11

Introduction to Cascading Style Sheets


11.1 The Role of Cascading Style Sheets (CSS)

Through these labs we have applied style formatting (fonts, colors, sizes, alignment, etc.) of text, tables, lists and other document elements by applying attributes or adding additional HTML tags to our document.  This process however, can not only be inefficient and complex, but inconsistent as well.

Consider the case of the development of a large web site.  Most web designers will create their site with a consistent look (or style) to the site where the paragraphs of text will have a consistent format, headers will have a consistent coloring and indentation, etc.  When working on a large site, it becomes rather difficult to ensure that the style of the site is properly applied.  In addition, if the web developer wished to change the style of the web site, they would potentially need to change each formatting characteristic in each file that comprises the web site.  Obviously, in a case like this, a better solution is needed.

That's where Cascading Style Sheets come in.  Cascading Style Sheets, or CSS as they are more commonly known, are used to define the formatting characteristics of an entire web site.  This is accomplished by associating an HTML element (such as a header) with style formatting information in a separate file (the CSS file).  Each page of a web site then is linked to the CSS file.  When a browser downloads a web page from the web site, the linked CSS file is downloaded as well, and the browser incorporates the CSS formatting rules into the rendering of the web page to be displayed.  By using style sheets, we separate the formatting commands in a web page, from the page's content.

Cascading Style Sheets are a recommendation of the World Wide Web Consortium (www.w3.org), which is the organization that develops the standards for use in the World Wide Web.  While we will cover some of the details of Cascading Style Sheets here, there is a lot we won't be able to cover.  If you find yourself in search of more information about CSS, check out the W3.org website for more information!

11.2 Our First Style Sheet

Supposed that we wanted to make all of the level one headings to be rendered in red.  We would create a CSS file that contained the following rule:
H1 { color: red }
CSS rules are comprised of two parts: a selector (the portion to the left of the braces) and the declaration (the portion within the braces).  The selector links an HTML document element to a style (defined by the declaration).  With this setting, all renderings of text using the <H1> tag in an HTML document will display the text in red.

CSS rule declarations are comprised of two parts as well: a property and a value (similar to HTML attributes).   Rule declarations can contain multiple properties and values by separating them with a semi-colon.  For example, we can expand the H1 rule shown above to set a background color as well:
H1 { color: red ; background: yellow }
We can also combine selectors to save space, if the selectors in question have the same declarations.  For example, we can rewrite the following:
H1 { color: red ; background: yellow }
H2 { color: red ; background: yellow }
H3 { color: red ; background: yellow }
as:
H1, H2, H3 { color: red ; background: yellow }
CSS files are simple text files with a .css file extension.  Once we have a CSS file created, we need to associate our web page to the file.  This is performed by adding the HTML link tag (<link>)to our source code file.  We do this by placing the following line of code within the header tag of the web page we wish to associate with the style sheet.
<link rel="stylesheet" type="text/css" href="style.css">
The three attributes used above are necessary to obtain the desired result.  The rel attribute informs the web browser that we are linking to a stylesheet file.  The type attribute informs the browser what language the style sheet is encoded in, and the href attribute is an absolute or relative URL to the style sheet we wish to link to.

We have modified the style sheet file to contain the following rules:

styles.css
body { font-family: sans-serif }
h1, h2, h3 { color: red ; text-decoration: underline }

The first rule sets the type of font with which the web page's contents are to be displayed.  Here, we are using a sans-serif font.  Browsers have access to at least three types of font families: serif, sans-serif, and monospaced.  The actually font name to use could also be specified, but since we might not be sure that the browser will have access to it, we'll only specify which font family to use, and let the browser decide the actual font.

Our second rule sets the foreground color to red and applies underlines to the H1, H2, and H3 HTML tags in our document.  Figure 1 shows a screen capture of the result of these changes on the Cat Window Lounger product page from our e-store.

Applying a Cascading Style Sheet to our web page.
Figure 1: Applying a Cascading Style Sheet to our web page.

Lab Activity #1:
Create a Cascading Style Sheet for use with your web pages and link it to no less than three web pages.

Use the body rule to select a serif-based font, and the H1, H2, and H3 rules to display your headings in blue text with a green background.


There's quite a bit of information to cover when dealing with CSS, as it provides quite a broad range of formatting capabilities.  All of the formatting tags we covered in the earlier labs are essentially replicated in one form or another through the use of a wide variety of declarations.  We don't have the means to cover them all here, but will certainly discuss additional declarations as we move forward.

If you would like more information about the various declarations possible in a CSS file, be sure to look at the World Wide Web Consortium's CSS2 Specification page.  Additionally, there is a fantastic web site dealing with CSS development called 'The House of Style', located at www.westciv.com (be sure to check out their section on properties).

11.3 CSS Selectors

If you haven't noticed yet, we've created our selectors based on the names of HTML tags.  Thus far, we have applied formatting for the body and H1/H2/H3 HTML tags.  Since we can create selectors for any HTML tag, we can now expand which tags can have formatting applied to them.  For example, we can now create a selector for the paragraph tag (<p>).

These are known as type selectors and will match every occurrence of the tag they match.  However, sometimes this may be overkill.  Perhaps we would like to occasionally match the tag in question.  CSS provides a mechanism for achieving this as well, known as attribute and class selectors.  We will cover each in turn.

Attribute selectors follow a type selector and are enclosed in brackets.  While there are several forms of attribute selectors, the two we will cover include matching if an attribute of a type is set, and matching if an attribute is set and contains a certain value.  For example, we have added the following selector to our style sheet file:
a[href] { background-color: pink }
This creates a pink background color surrounding any HTML tags that take the form of <a href...> (and anchor tags that create links).  We can also write our attribute selector to be more specific, by looking for tags that link to petdental.com by inserting an equal sign and the value to match:
a[href="http://www.petdental.com"] { background-color: lightgreen }
Now, if we view the main page of our web site we see the result shown in Figure 2.  It's not very attractive, but it gets the point across about our selectors.

Using attribute selectors
Figure 2: Using attribute selectors.

Another type of CSS selectors are class selectors.  Here, we can apply a class attribute to an HTML element to include the tag (conceptually) in a group of similar tags all of which share the same class name.  For example, we can have several paragraphs each in the "right" class, which we will use as a selector to make them displayed right aligned.  To accomplish this, we add the class="right" attribute and value string to the <p> tag as in:
<p class="right">This text will be right aligned.</p>
To actually implement the right alignment directive, our style sheet file would need the following entry:
p[class="right"] { text-align: right }
Alternatively, we can write the following:
p.right { text-align: right }
(The text-align property accepts the following values: left, center, right, and justify.)

Yet another type of CSS selectors are id selectors.  ID selectors operate the same as class selectors do, with one exception.  While you can have multiple HTML tags that are in a specified class, you can have only one HTML tag with a particular id value.  For example, if we create a paragraph in our HTML source code that appears as:
<p id="quote">The quick brown fox jumped over the lazy dog.</p>
We can not have another paragraph in the same HTML document with the same id value (quote).  You can match a id attribute to its selector in a style sheet file by appending the tag name with a "#" and then the id value.  For instance, to match the paragraph above, we would do:
p#quote { margin-left: 5% }
creating a left margin of 5% of the width of the element's available horizontal space.

We will use this technique to modify how our product descriptions are displayed.  In each of our product pages, we will change our product description source code to be of the form:
 <td colspan="2"><b>Description:</b> <p id="description">Product Description goes here!</p>
We will also add the following line to our style sheet.
p#description { margin-left: 5%; margin-right: 5%; text-align: justify }
With these rule, we will add 5% margins of both sides of the text that is in the description paragraph, as well as perform a full justification.  A snapshot of the results for the Cat Litter Scooper product is displayed in Figure 3.

Using id selectors.
Figure 3: Using id selectors.

Lab Activity #2:
Implement two attribute selectors and two class selectors in the cascading style sheet for your web site.  Which ones did you create? _______________

Use the World Wide Web Consortium's CSS2 Specification web site to list other types of CSS Selectors.
How many others can you find? __________
What are they?  _______________________________

11.4 CSS Properties and Values

As you can likely guess, there are quite a number of properties and values that are available to use when working with style sheets.  In fact, there are more than 50 different types of properties in CSS, and that's excluding several advanced properties that allow the web page designer to overly text and graphics on top of each other.

Rather than cover each one, we have categorized the CSS properties into 5 groups and picked some of the more popular properties to expand upon.  Once you really start taking advantage of the power of Cascading Style Sheets, you'll want to refer to a more complete guide to all of the properties (several were mentioned above).


Properties for controlling the appearance of text

Property Name
Permitted Values
Description
color
  • color name - e.g. red, blue, green;
  • hex code - #33CCFF; or a
  • RGB value - rgb(0, 255, 255)
Sets the foreground color for the desired element.  For text this would be the text 's color.
font-family
Font family name: serif, sans-serif, cursive, fantasy, monospaced
Font name (in title case): e.g. Arial, "Times New Roman" (note quotes when the name contains whitespace)
Specifies the font to use.  Can be a comma separated list of fonts or font families in order of preferred use).
font-size
Length values: by pixel (e.g. 3px), millimeter (e.g. 3mm), centimeter (e.g. 3cm), inch (e.g. 2in), etc.
Absolute values: larger, smaller
Relative values: xx-small, x-small, small, medium, large, x-large, xx-large
Specifies how large text will be rendered.
font-weight
Absolute values: normal, bold
Relative values: bolder, lighter
Specifies how heavy (bold) a font will be rendered.
text-transform
capitalize, uppercase, lowercase
Sets the capitalization of an element's text.
text-decoration
underline, overline, line-through, blink
Applies one or more decorations to an element's text.  Multiple values can be concurrently applied by specifying their names separated by a space.

Properties for controlling the layout of text on a page
Property Name
Permitted Values
Description
text-indent
  • Length values: by pixel (e.g. 3px), millimeter (e.g. 3mm), centimeter (e.g. 3cm), inch (e.g. 2in), etc.
  • Percentage values: percentage of the space of the containing element. (e.g. 5%)
Defines how the first line of any element is indented.  Outdenting can be achieved by using a negative value.
text-align
left, right, center, justify
Defines how an element's contents are horizontally aligned.

Properties for backgrounds
Property Name
Permitted Values
Description
background-color
  • color name - e.g. red, blue, green;
  • hex code - #33CCFF; or a
  • RGB value - rgb(0, 255, 255)
Sets the background color for the desired element.  Any HTML element can have a background color by using CSS.
background-image
A URL to the image file, relative to the CSS file on the web server.
Sets the background image for the desired element.  Any HTML element can have a background image by using CSS.

Properties for borders
Property Name
Permitted Values
Description
border-width
thin, medium, and thick
Sets the thickness of the border.  Medium is the default.
border-color
  • color name - e.g. red, blue, green;
  • hex code - #33CCFF; or a
  • RGB value - rgb(0, 255, 255)
Sets the color of the border that surrounds the element.  
border-style
none, dotted, dashed, solid, double, groove, ridge, inset, outset
Sets the style that the border is drawn with.

Properties for margins
Property Name
Permitted Values
Description
margin-top
  • Length values: by pixel (e.g. 3px), millimeter (e.g. 3mm), centimeter (e.g. 3cm), inch (e.g. 2in), etc.
  • Percentage values: percentage of the space of the containing element. (e.g. 5%)
Sets the amount of the top margin for the element.
margin-left
  • Length values: by pixel (e.g. 3px), millimeter (e.g. 3mm), centimeter (e.g. 3cm), inch (e.g. 2in), etc.
  • Percentage values: percentage of the space of the containing element. (e.g. 5%)
Sets the amount of the left margin for the element.
margin-bottom
  • Length values: by pixel (e.g. 3px), millimeter (e.g. 3mm), centimeter (e.g. 3cm), inch (e.g. 2in), etc.
  • Percentage values: percentage of the space of the containing element. (e.g. 5%)
Sets the amount of the bottom margin for the element.
margin-right
  • Length values: by pixel (e.g. 3px), millimeter (e.g. 3mm), centimeter (e.g. 3cm), inch (e.g. 2in), etc.
  • Percentage values: percentage of the space of the containing element. (e.g. 5%)
Sets the amount of the right margin for the element.

By utilizing some of the properties above and applying our styles to the menu web page and all of the product web pages, we can create a consistent look-and-feel to our pages, as well as create a more pleasing appearance.  The modified style sheet file is shown below, followed by a screen capture of our store with the resulting changes.

styles.css
body.product { background-color: #CCCCFF }
body { font-family: sans-serif }
h1, h2, h3 { color: red ; text-decoration: underline }
p.border { font-weight: bold; text-align: center; border-color: red; border-width: thin; border-style: solid }
p#description { margin-left: 5%; margin-right: 5%; text-align: justify }
table.purchase { border-color: #CCCCFF; border-width: thin; margin-left: 20%; margin-right: 20% }
b.price { border-style: double; border-style: normal; border-color: white; }


The e-store with our style sheet changes.
Figure 4: The e-store with our style sheet changes.

Lab Activity #3:
Select five of the properties defined above and include them in your style sheet.  Which properties did you select?
  1. ____________________
  2. ____________________
  3. ____________________
  4. ____________________
  5. ____________________
Using the World Wide Web as a resource, locate a tutorial (which was not mentioned in this lab) dealing with Cascading Style Sheets.  Select five additional properties from the tutorial that were not listed in the table above.  Which properties did you select?
  1. ____________________
  2. ____________________
  3. ____________________
  4. ____________________
  5. ____________________
Apply these additional properties to your style sheet, and incorporate the style sheet modifications into your web pages.

11.5  So where is the cascading part?

Cascading Style Sheets have another interesting attribute to them that we have conveniently skipped over until now.  Essentially, they can be linked together (import one CSS into another) such that their rules cascade from one sheet to another.

This can be a powerful tool when a large number of web pages are being developed by multiple developers and some separation of rules is necessary.  For example, assume we have two web developers creating pages for a new site and each needs to create a specialized style sheet for their portion of the web site, yet each will share some common rules.

The common CSS rules can be placed in one file (assume they will name it topLevel.css).  Then, each developer can create their own CSS files with their own more specific rules.  For instance, each developer may need to create rules for the H1 tag, but have different formatting requirements.  Obviously they will each need to create their own rules for the H1 tag.  However, they don't wish to duplicate the rules which are shared between them, since it would be inefficient (not to mention a major pain to change the rules in both files if modifications needed to be made).

To link their individual files to the shared CSS file (topLevel.css), each developer will include the @import statement in their CSS file.  The @import statement specifies the location of another Cascading Style Sheet to include in the enclosing sheet.  The statement has two forms, as demonstrated below.  In each case, we provide the location of the CSS file to import.
@import url(http://www.petespets.com/topLevel.css);
or
@import "http://www.petespets.com/topLevel.css";
Cascading can also help to organize a large number of CSS rules.  You can create one file for rules related to tables, one for text, one for headings, and another for forms.  In this manner, you can keep your CSS rules neatly organized.

Lab Activity #4:
Create a second CSS file for your web pages, and place half of your CSS rules in the new file.

Then, import the new file into the old file.


About the labs:
These labs were developed in conjunction with the Jones and Bartlett textbook Computer Science Illuminated by Nell Dale and John Lewis.
ISBN:  0-7637-1760-6
Lab content developed by Pete DePasquale and John Lewis.
 
Educators: More Information About This Text Other Computer Science Titles at Jones and Bartlett
Copyright 2019 Jones and Bartlett PublishersContact webmaster