(Reading: We strongly suggest you read chapters 8 and 9 of Head First HTML with these notes.)
When HTML was first introduced, there were a number of tags whose purpose was just for formatting: for example, tags that center or switch to an italic font. With HTML version 4.0, such tags were made obsolete (though most browsers still support them), in favor of a formatting technique called Cascading Style Sheets.
When a browser is displaying a page, there is a step of reading a
tag, such as <em> or <h1> and
then determining what the results are to look like. (This is
sometimes called rendering a page.) Each browser has a default
way of rendering a tag. For example, most browsers will render the
<em> tag by switching to an italic version of the current
font. Most browsers will render an <h1> tag by switching
to a very large version of the current font. There are several important points
to make about this:
<blockquote> in Safari
indents by a different amount than IE does.
<em> tag to look red, you can do that. The style of tags
is determined by something called CSS, for Cascading Style
Sheets.
You can specify the style of a tag using a style sheet. These style sheets can be put in (at least) three different places:
<head> of a document, using a special
tag.
<link> tag. You saw an example of this previously,
and if you view the source for this web page, you'll see
another example.
Suppose that we always want <em> to be red. After all,
em stands for emphasis, and what could be better emphasis
than putting something in red? (FYI, using color is, in fact, a
terrible idea, because some people are color-blind or even
completely blind. We'll talk more about the issue of accessibility as the need arises
throughout this course. You should always think about
accessibility when you are designing a web page, because you want your
page to be readable by anyone, not only by people with the same
physical abilities, browser software, computer display, and network
bandwidth that you have. Some websites are legally required to be
accessible. However, for the purposes of this lecture's examples,
let's suppose that using red is a sensible thing to do.) Let's look
at the three ways to make <em> red:
style
attribute of the tag to set the color
property to have the value red and the
background property to have the value white.
(You should be reminded of the attribute/value idea in tags, but
the syntax is different. With CSS, attribute/value pairs are
separated by semi-colons, and the attribute ends with a colon.)
Note that you should always pick both colors, in
case the user's browser has specified a background color that
matches your foreground color. Here's the example:
this is an <em style="color: red; background: white">important</em> wordresults in
this is an important word
<style> tag in the <head> of your
document to specify the style for the <em> tag once and
for all:
<style type="text/css">
em {
color: red;
background: white;
}
</style>
Later in your document, you just use the <em> tag
normally, and it's rendered as red.
<style> tag. Instead, you
reference the file using the <link> tag in the
<head>, the same place you would use the
<style> tag. Suppose we create a file called
my-style.css that contains the following:
em {
color: red;
background: white;
}
and we reference it in the <head> like this:
<link rel="stylesheet" type="text/css" href="my-style.css">
As with document-level style sheets, we can just use the <em> tag
normally from then on.
There are several facets to the syntax of styles:
color) are followed by
a colon, then at least one space, then the value of the property (such
as red). The only properties we've learned so far
are color and background (which is a
shorthand for background-color), but we'll learn more
soon. The discussion of fonts will cover font properties such
as weight and size, for example. If you
want to specify more than one property/value pair, separate them with
semi-colons. If there's only one property/value pair, the semi-colon
is optional. (Many people put it in just in case they add another
property/value pair later.) The order of the style properties does
not matter.
style attribute. Remember to enclose
the style properties within quotation marks.
p or
em) that you are modifying goes first, then an
opening brace, then the style properties, then a closing brace.
Spaces and line breaks are ignored, so feel free to format this in
a visually pleasing way. As always, clear and consistent
indentation is very helpful for any reader of your styles.
Conventionally, the tag is upper case and the style properties are
lower case.
<style> tag, while external style sheets always omit
the <style> tag.
<style> tags. You'll have nothing in angle brackets in
an external CSS file.
/* to
begin and */ to end. Thus, for an external style
sheet, you might have:
/* Written by the CS110 Faculty
Fall 2005
*/
em {
color: magenta;
background: white;
}
Please do the first exercise described in this CSS Example
Create a small web page containing the following content:
<html>
<head>
<title>Solution to Exercise 1</title>
</head>
<body>
<p>This is the first paragraph of my little page.
It should be green since
we modified the style of the P tag.
<p>Here's a <strong>second</strong> paragraph,
and it uses the
<strong>STRONG</strong>
tag and also a
<em>customized</em>
EM tag. We can also, just for fun,
<strong> see what <em>nesting</em> elements</strong> does.
<p>Here is the take-away message: you have power over
presentation!
</body>
</html>
Please do the following:
em tag so that it is red, using inline styles.
strong tag so that it is blue, and has
a font-size of 200% (doubling the font size).
Do this using a
document-level style sheet.
p tag so that it is green, using an external
style sheet called style.css
em and strong in the second paragraph.
CSS has “cascading” in the title because there's a
strict hierarchy that determines which specification applies if the
style of a particular tag is set in more than one place. Suppose you
specified the <em> tag as green in an external style sheet,
blue in a document-level style sheet and red in an inline style.
Which wins?
The simplest answer is that the closest specification wins. This makes sense, because you can use the more local specifications to override the more distant, global specifications. So, inline style attributes beat document-level sheets, and document-level sheets beat external style sheets.
Furthermore, properties from enclosing elements can be inherited by the
elements inside them. Notice how, in the exercise,
the <em> element inside
the <strong> element inherits the font size.
If you'd like all the technical details of the cascade, you can check the specifications of cascade order. The Head First HTML book also describes this in more detail than you probably want.
One of the most common rules of thumb for creating clear and beautiful documents is consistency. For example, section headers should always be the same size, weight and font. Indeed, this is what a “style sheet” means in the context of document processing. MS Word format files are the same thing.
You can best achieve consistency by specifying the style far enough from the text so that the style is specified in just one place. If you have a single web page that you would like consistent, you should use a document-level style sheet. If you have several web pages (a web site) that you want to be consistent, you should definitely use an external style sheet. Even if your website is only a single web page but you think you might someday have a second web page using the same style, you should use an external style sheet. In short, always use an external style sheet.
In this course, you and a partner will be creating a website
for a client. For that website, you should define an external style
sheet. Then, if you or your client decides that <h1>
should be centered, <h2> should be bold and blue,
<h3> should be underlined and non-bold, and <em>
should be pink, you can do that in one place. If you later change
your mind and decide that <em> should be purple, you make
one change in one file and all of your website is consistently and
instantly changed. If you had used the local style technique, you
would have to edit every page of your site, searching for and
modifying each occurrence. This is tedious and error prone.
Because the CS110 faculty would like our (very large) course website to be consistent, we will be using a CS110 style sheet throughout. (But we may not have fixed all the web pages yet; we're migrating from a non-CSS website. Please point out any errors that remain.)
We will often use inline styles and document-level style sheets for examples because it reduces the number of files to edit in order to show something, but in practice you should almost never use these. (Indeed, the Head First HTML book never uses inline styles at all.) We will show you some techniques that allow you to get the same effect as an inline style or document-level style while retaining the ability to keep all style information in an external file.
The idea of CSS illustrates an important concept in the field of
computer science, namely abstraction. Abstraction is the
idea of saying what you want done without saying how to do it. By
leaving out the details about how to do something, you allow for some
flexibility, so that you can revise your method of doing the task
without messing up anything that depends on that task being
done. Here, we said <em> without saying what that meant,
putting elsewhere the specification of how to emphasize.
So far, we've achieved an effect by modifying one of the existing tags,
mostly <em>. Suppose you want to make some text a
different color,
but it's not emphasis, so it feels wrong to use
the <em> tag. As another example, in the title of
the color
lecture we used several colors of text (just to be cute). How did we
do this using CSS? The answer is a new tag called
<span>. By itself, <span> does nothing. Its
only purpose is to support the style attribute so that
you can modify the appearance of the stuff between start and end
<span> tags. It's a pretty intuitive name for the tag. If
you view source, on the color lecture, you can see how we did
this.
Suppose that we're using a special word and we want just that special word to be rendered differently. We could say:
The word <span style="color: teal; background: white">
Supercalifragilisticexpialidocious </span>
is a special word
and the result would look like:
The word Supercalifragilisticexpialidocious is a special word
Thus, we don't have to press <em> or <strong>
into a job they're not suited for; we can just use <span>
whenever we want to modify the style of something.
This is an important point, so we want to bring it out: The purpose
of the HTML tags are to convey the structure and
meaning of the content of your site, so you do not
use <em> for something other than emphasis. Only use a
tag that conveys the correct meaning of its contents.
For example, don't use <h1> just to switch some text
to a big font; reserve it for something that is a
header, indeed, the major header.
<span> is intended for stuff within a
paragraph, so when you use <span> there is no break
in the paragraph. If you want to start a new paragraph, you
are probably defining some big division of your document and you
should use the <div> tag. For example, you might
be defining the appearance of the abstract, the bibliography, a
theorem, a glossary entry, or an exercise. For
that purpose, you can use the <div> tag. Like
<span>, it exists primarily to carry a style sheet.
(There are other uses that we'll omit.) The difference is that
div is a display object, meaning that using it
is separated by vertical space from the preceding and following
material, like a paragraph.
There is an important pitfall in using <span> and
<div> this way. Suppose we are creating a web page that
involves a number of special terms. Maybe they're trademarked terms,
for example. If we use <span> each time they occur, we can
control how they look, but if we later change our minds about the
presentation, we'd have to go back and find all occurrences and change
them. This is just the thing that CSS should solve.
We want to set these special terms off somehow, but we don't want to use
<em> or <strong> or even
<dfn> (there is such a tag, used for terms you are
defining). We wish there were a tag called <tm>,
but there isn't. If there were, we could modify the style for
<tm> and use that.
One option is to use style classes. For example, in our document-level style sheet we could write:
<style type="text/css">
span.tm {
color: maroon;
background: white
}
</style>
Without the surrounding <style> tag, the specification of
span.tm can also be placed in an external style sheet. Within the
document, we can write:
Remember that <span class="tm">Coke</span> and <span class="tm">Pepsi</span> are both registered trademarks.
With the result looking as we want:
Remember that Coke and Pepsi are both registered trademarks.
If we later decide that instead of maroon, all the trademarked items should be red or even black (so that they no longer stand out), we can again change this in just one place.
Note that we defined our class by what the item is, not what it looks like. The code of our document is only about the content, not the appearance. Appearance information is only in the style sheets. This separation of content from appearance is an important aspect of the concept of abstraction, which we discussed earlier.
Consider the alternative. Suppose that instead of defining a class
called tm for our trademarked terms, we defined a
maroon class and used that. If we later changed our
minds and decided to make them pink, we'd have the bizarre result that
the class named maroon makes things pink. Read more
about good class
names.
The CS110 web pages use <div> and
<span> in this way, using the ex
class, to define the format for exercises in these lecture notes.
View the source to see the markup tags.
You can use classes to modify the presentation of any tag, not just
<span> and <div> . For example,
you might have certain headers you want to be different from other
headers, say appendices or optional sections. You can then define
classes such as:
H2.appendix { ... }
H2.optional { ... }
H2.preamble { ... }
You would use these in your HTML file like this:
<h2 class="optional">Obscure Connections</h2> <h2 class="appendix">Bibliography</h2>
Here is how the section classes might look.
Please do the second exercise described in this CSS Example
Return to your small web page from exercise 1 and do the following:
style2.css.
important. The font in important paragraphs should be
bigger, which you can do like this:
font-size: larger;
detail. For that, make the font smaller:
font-size: smaller;
takeaway. For that, make
the font-size 25px.
font-size: 25px;
important class to the first
paragraph and the detail class to the second paragraph.
Apply the takeaway id to the last paragraph.
There are two facets to the syntax for defining and using style classes:
<span>, <div>,
<em>, and <h1>.
Then a dot (period) and then the name of the class you are
defining. There are no spaces on either side of the dot.
Traditionally, the name of the tag is uppercase and the name of
the class is lowercase, but this is merely convention. Then
define the style as usual within braces.
class, then an equals sign (spaces are
allowed but usually omitted), then the name of the class in quotation
marks.
As we get to more complicated CSS, debugging it can sometimes be very difficult, as the layout rules can be a little unintuitive. Fortunately, there are some tools that can help.
The first tool is the browser's error console. Whenever a browser encounters something it doesn't expect or doesn't understand, it generates an error message. However, it hides those error messages from the human user, since 99.99% of people viewing the website aren't developers and don't care about errors. But you're a developer and you care, so look for the error messages.
In Firefox, look under
Tools > Error Console.
The next tool is the HTML and CSS validators. Don't try to debug invalid code! Make sure it validates before struggling to get it to behave properly.
Finally, there's my favorite: Firebug. Firebug is is a plugin for Firefox. Get it, use it, enjoy it. It's awesome.
One of the great advantages of external style sheets is also, for a web developer, a slight bother. To understand that, you have to understand caches.
The word “cache” (pronounced “cash”) is an ordinary, but uncommon, English word (more of an SAT word for most people). However, it's used all the time by computer scientists because caches are used all the time by computers, in all kinds of ways, because caching is a general technique for speeding things up.
In particular, your web browser will cache (keep a copy of) an external style sheet in a folder on your local machine (that folder is called, of course, the cache). If the web browser needs that style sheet again, say on another page of your site that uses the same external style sheet, the browser doesn't have to re-download the file; it just grabs a copy from the cache. This makes the web browser faster.
So, why is the browser cache a problem for a web designer? Because if you make a change to the external style sheet, the web browser may continue to use the old cached copy, instead of getting the new improved copy from the server. This means that when you view your page, you won't see your changes — very frustrating.
The solution is to tell the web browser to ignore the cache when you re-load the page. In most web browsers, this is done by holding down the shift key when you click on the reload icon.
So, just remember:
When in doubt, use shift+reload
Students often wonder about what the difference is between a class and an id, and when to use each one. The key is uniqueness: an id must be unique, while a class describes a kind/type/category of element.
For example, there might be many occurrences of these classes of elements:
On the other hand, there is probably only of the following elements per page, so these might have an id.
The uniqueness of an id makes them suitable as the fragment
in a URL, so you can link to that particular element of a page.
Here's a picture showing an id being used once and a class being used thrice. Also note the syntax: pound signs for ids and periods for classes.
Please inspect the following two examples of classes and ids, one using students and the other using faculty. Use Firebug on them!
Here are some examples of using CSS to customize a tag.
A:link {
color: lime;
background: white;
}
The :link part is called a
pseudo-class.
:visited
pseudo-class for the A tag:
A:visited {
color: olive;
background: white;
}
list-style-position: inside to make
the bullets run into the paragraph, instead of being outside,
which is the default behavior. For more, see the CSS2
reference on lists
display property to inline. Read
more about formatting
lists in CSS.
We have only scratched the surface of CSS. There is much more to learn, and we'll learn some more in a future lecture. You can also teach yourself more from
View another example of the application of basic CSS concepts to the styling of a simple web page about introductory CS courses.
Some additional CSS examples were created by Lyn Turbak.
Be amazed by CSS Zen Garden
To be horrified, check out WebSitesThatSuck.com