User:Bartlett/02

Ka Wiktionary

Hour 2. Getting Started with CSS[wax ka badal]

What You'll Learn in This Hour
  • What kinds of tools, from text editors to CSS software, you can use to write your style sheets
  • How to create, name, and save a style sheet
  • What the different parts of a CSS rule are and the function of each
  • How and when to add comments to a style sheet
  • Which simple rules you can use to create a basic style sheet
  • How to apply your style sheet to a simple HTML file
  • Which browsers to use to test your style sheet


Creating a Style Sheet[wax ka badal]

A Cascading Style Sheet, as you learned in [Hour 1], "Understanding CSS," is simply a file made up of style rules. CSS files are ordinary text files, just as HTML files are ordinary text files. This means that you can use a wide variety of programs to create a style sheet, from simple text editors to specialized software written just for creating and maintaining style sheets. Anything that can be used to create a text file can create a style sheet.

Because Cascading Style Sheets are pretty simple to write, you don't need to use complex tools to create a basic style sheet. Many web developers will write CSS by hand, meaning that they type out the text of each rule; however, authoring tools exist that can make this task easier.

Software Tools for CSS[wax ka badal]

Your editing environment is the program or set of programs that you use to create your style sheet. You'll want to choose the editing environment that works best for you, be that a text editor, a style sheet editor, or a web development tool. I use a text editor myself, and I recommend starting simple, at least until you've learned enough about the basics of CSS to understand how editing tools can help you.

Text Editors[wax ka badal]

Every operating system comes with a basic text editor, and because CSS is just basic text, it's a good match for one of these programs. A text editor is a simple program that just produces plain text files, which means it can also be used to create HTML or CSS files. Unlike word processing software, text editors don't save formatting with the text; that's why they are said to produce plain text. Text editors are ubiquitous and don't get in the way of your learning about CSS, so this is probably where you want to start. You probably already know how to use one of the text editors on your computer. Some basic text editors include

  • Notepad or WordPad on Microsoft Windows
  • TextEdit on Macintosh
  • vi, vim, or emacs on Linux or Unix

[Figure 2.1] shows a style sheet being edited in Notepad on Windows; this is the style sheet from the author's personal website, which was shown in [Hour 1]. Don't worry too much about reading and understanding the properties; the style sheet is rather complex and has a lot of properties from the middle or end of this book.


Did you Know?
You can use a word processing program, such as Microsoft Word, to create text files, but you need to remember to save your files as plain text without any special formatting. It's probably easier to just use a text editor, although most of them lack the advanced features found in word processors, such as advanced find-and-replace and word counting. Fortunately, you'll rarely need those features when editing CSS.

Style Sheet Editors[wax ka badal]

Some software has been written specifically to create CSS style sheets; these have advanced features such as color-coding of rules and properties, syntax checking, and more. These are great tools, and I highly recommend them when you're doing serious CSS development; if you're just beginning, though, they may be more than you need right now and could overwhelm you with options. After you understand the principles and language of CSS, however, a style sheet editor is invaluable. Some of the CSS editors available include

The screenshot in [Figure 2.2] shows the author's style sheet being edited in Style Master, one of the CSS editors listed here. As you can see, a style sheet editor offers a lot more in the way of development features compared to a simple text editor, but it's also more complex to use.

HTML Editors and Web Development Software[wax ka badal]

Because CSS is an integral part of web design, web design packages that let you create HTML often support CSS editing. Visual editors let you set styles and create the style sheet behind the scenes, whereas those with source editing modes enable you to edit the style sheet directly. As with CSS editors, I recommend using these after you've become familiar with the basics of CSS syntax. Your favorite web editing environment may already include CSS support; some that do include

Naming and Saving a Style Sheet[wax ka badal]

However you edit your style sheet, the basic principle will be the same: You create a text file that contains the CSS rules, and you save that as a CSS file. Your style sheet's filename shouldn't contain spaces, so that it will be easier to use on the Web.

The extension you should use is .css, so your files should be named something like test.css or sitedesign.css. While you're learning and practicing, you'll probably want to keep the .css file in the same directory as your HTML pages. After you've got the hang of CSS, you'll probably want to store your style sheets in a designated directory on your website; I usually create a /styles/ directory for mine.

Writing CSS Rules[wax ka badal]

The building blocks of any style sheet are the CSS rules that compose it. Each rule is a single statement that identifies what should be styled and how those styles should be applied. Style sheets are then composed of lists of rules, which the browser uses to determine what a page should look like (or even sound like).

The Basic Structure of a CSS Rule[wax ka badal]

A CSS rule consists of two sections: the selector(s) and the declaration(s). A declaration is made up of a property and a value for that property. A simple CSS rule would therefore look something like this:

selector { property: value; }

One important thing to note is that CSS ignores extra whitespace, just as HTML usually does. This means that as far as CSS-enabled browsers are concerned, one space is equal to twenty spaces or even five spaces, four blank lines, and four more spaces. So the rule could be written like this and still mean the same thing:

selector
 {
 property:
 value;
 }

You should feel free to use whatever spaces and lines you need within your CSS to make it easy to read and maintain. For example, I usually indent the property and value pairs quite a bit by inserting spaces; this makes it easier for me to see at a glance where one rule ends and the next begins. By being consistent in how you use blank spaces in your style sheets, you can keep them easy to read and maintain. There is no one best way to write a style rule, and you may end up using different spacing in different situations. As long as it works for you, that's what matters.

The Selector[wax ka badal]

The selector part of the rule tells which section of the document the rule covers. The simplest type of selector is a type selector that indicates a specific markup element, such as the <p> tag in HTML. You write a type selector by just giving the name of the element without the <> brackets, as in the following:

p { property: value; }

Such a rule would select the styling of all <p> tags.

The Declaration[wax ka badal]

The next part of the rule is the declaration. Declarations are enclosed in {} braces. Within the braces, the property name is given first, followed by a colon, and then a property value. An ending semicolon is optional but recommended for reasons that will become apparent later this hour. The entire rule is concluded by the ending brace.

Properties[wax ka badal]

Properties are defined by the official CSS specifications; these are the specific style effects you can define and expect to be supported by CSS-compliant browsers. Most browsers are likely to ignore properties that aren't part of the CSS specification, although some browsers recognize nonstandard properties that are not part of the formal language specification. It's best to not rely on these proprietary extensions, but browsers that don't recognize them simply overlook them. In [Hour 3], "Browser Support for CSS," you'll learn more about how browsers handle or don't handle CSS.

Values[wax ka badal]

The value of the declaration follows the property name, after the colon, and defines exactly how that property should be set. The range of values for each property is also defined in the CSS specifications. For example, the property named color can take values that consist of color names or codes, as in the following:

p { color: blue; }

This rule declares that the content of all paragraph tags should have their color properties set to the value blue. So all <p> text would turn blue.

By the Way
What happens if you don't set the color? Well, you can probably guess from your work with HTML that a default will be chosen—one set by the browser or the user's preferences. The color might also be set by the text attribute on the <body> tag, or on a tag. CSS adds additional ways to determine the color, including writing a rule with the <body> tag as the selector, which would then apply to all <p> tags within the <body>—that is to say, it would apply to all paragraphs on the page.

The specific process CSS uses to determine the color of the text or of any other property settings is called the cascade. You'll learn more about how the cascade works in [Hour 7], "Cascading and Inheritance."

Combining CSS Rules[wax ka badal]

You can combine two CSS rules that share the same selector by listing their declarations within the curly braces. The ending semicolon is no longer optional between two rules combined this way; it's a necessary separator between the two declarations. For ease of editing and combining, I suggest always including the semicolon even if your braces contain only one declaration.

Here's an example of two CSS rules with the same selector:

p { color: blue; }
p { font-size: large; }

These rules can be combined into one rule like the following:

p { color: blue; font-size: large; }

I could have also written the rule like this:

p
 {
 color: blue;
 font-size: large;
 }

That particular style of spacing makes it a little easier to cut and paste entire lines while writing or testing the CSS. The browsers don't care about the whitespace—it's there to help you organize your style sheet in whatever manner works best for you.

You can also combine rules if they have the same declarations and different selectors. You combine selectors by putting them in a list, separated by commas. For example, the following rules have the same declarations:

p { color: blue; }
address { color: blue; }

You can write them as one rule, as follows:

p, address { color: blue; }

This rule says, "The content of <p> tags and of <address> tags should be colored as blue text."

You can use multiple selectors together with multiple declarations; that is perfectly legal and very common. You can also write additional rules to further style those selectors together or separately. Here's what that might look like:

p, address
 {
 color: blue;
 font-size: large;
 }
p
 {
 font-family: Arial;
 }

CSS Comments[wax ka badal]

Like many other languages, including HTML, CSS allows you to embed comments in the source code. A comment is a special bit of code that you embed in your CSS that is completely ignored by the browser. Comments serve as a way of adding to the source notes that are meant for the author of the style sheet or someone maintaining it. The user doesn't ever see comments, and they won't affect the style of the page; they are significant only when reading or editing the style sheet itself.

Comments can be used to describe what your style sheet is doing at a particular point, or perhaps why it's doing it, so that when you come back to the style sheet later, you can recall why you wrote it that particular way. Comments are also useful for hiding sections of code that you feel you don't need any more or that you want browsers to ignore; this is known as commenting out your code. Comments can also be used to identify the author and the creation date of the style sheet and to provide a copyright notice.

Comments in CSS begin with the characters /* and end with the characters */. Anything between the start of the comment and the end is ignored. Here's an example of a comment:

/* Let's turn all the paragraph text blue */
p { color: blue; }

Your comments can appear anywhere you like, even inside a rule:

p
 {
 color: /* make it less blue */ purple;
 font-size: large;
 }

You can comment out parts of a declaration if you decide you don't want that particular part of the style rule to be applied, but you don't want to delete it. This is useful for testing various options when developing your style sheet. For example, this comments out the font-size declaration:

p
 {
 color: /* make it less blue */ purple;
 /* font-size: large; */
 }

However, you can't nest comments, meaning that if you try to enclose one comment within another, both comments end at the first */. For example, imagine that you want to comment out the color purple instead; if the comment markers are in the wrong place, as in the following, it doesn't work:

p
 {
 /* color: /* make it less blue */ purple; */
 font-size: large;
 }

In this case, the comment ends after blue, not at the end of the declaration. This leaves the word purple floating there outside the comment. CSS browsers will probably ignore it because a purple by itself doesn't have any particular meaning in CSS, but that's just lucky this time. You need to be careful when placing your comments so that you don't accidentally try to nest them.

Simple CSS Properties for Text Formatting[wax ka badal]

As you've probably surmised from the previous examples, there are CSS properties that can be used to set the text color, the size of the font, and the family of the font—color, font-size, and font-family, respectively. These are some of the simplest and yet most useful CSS properties; collectively, they perform the same function as the HTML <font> tag. Another very useful property is background-color, which sets the color of the background.

The color Property[wax ka badal]

The color property is used to set the foreground color of the element, which is the property controlling the color of the text. For example,

h1 { color: lime; }
h2 { color: red; }

This makes all <h1> elements a bright, lime-green color and makes all <h1> elements red. As with HTML, you can use one of 17 standard color names, or you can give an RGB value, such as #FF0000. The color names and their corresponding RGB values are shown in [Table 2.1].

Color Name RGB Value
aqua #00FFFF
black #000000
blue #0000FF
fuchsia #FF00FF
gray #808080
green #008000
lime #00FF00
maroon #800000
navy #000080
olive #808000
orange #ffA500
purple #800080
red #FF0000
silver #C0C0C0
teal #008080
white #FFFFFF
yellow #FFFF00

The background-color Property[wax ka badal]

You can use the background-color property to set the background color. The values are the same as for the color property—color names or RGB values. To set the background color for the whole page, use the <body> tag in your selector; you can set backgrounds on any other elements as well. For example,

body { background: silver; }
h1 { background: #FFFF00; }
Watch Out!
When you set the background color, make sure you've also set a foreground color that is visible against it! Otherwise your text may be very hard to read.

The font-size Property[wax ka badal]

The font-size property enables you to specify the size of the text that's displayed to the user. One of the easier ways to specify font sizes is to give a value relative to the user's default text size; this respects the user's preferences as set in the browser.

The default text size has a value of normal; larger sizes go up in increments of about 20% to values of large, x-large, and xx-large. Smaller sizes decrease by 20% to small, x-small, and xx-small. You can also use the relative values larger and smaller to indicate one step up or down the scale from the current size. Here are some examples:

dl { font-size: large; }
caption { font-size: small; }
em { font-size: larger; }

The font-family Property[wax ka badal]

You can use the font-family property to set the font face of the text. So why is it called font-family and not font-face? When you designate a font, you're really designating a whole family of related variants within the same font family. So when choosing Arial font, you're actually choosing the Arial family of fonts, each one slightly different in size.

CSS also uses generic font families. The generic font families are sans-serif, serif, monospace, cursive, and fantasy. These aren't names of specific fonts, but rather a broad class that can be used as defaults if the browser doesn't know what a font name represents. If you choose a font that isn't installed on the user's machine, the browser uses just the normal font, so make sure you designate a generic font family as well as a specific one. You indicate the generic font by listing it after the specific font, separated by a comma.

Common web fonts and their generic families are shown on [Table 2.2].

Font Generic Font Family
Arial sans-serif
Times New Roman serif
Courier New monospace
Verdana sans-serif

If the name of the font family has more than one word, enclose it in quotes. Here are some examples of CSS rules that use font-family:

body { font-family: Arial, sans-serif; }
h1 { font-family: "Courier New", monospace; }
h2 { font-family: "Times New Roman", serif; }

You'll learn more about font families and font sizes in [Hour 9], "Fonts and Font Families."

A Simple Style Sheet[wax ka badal]

Using just the simple properties and values you've learned so far this hour, you already can create a basic style sheet; an example of a complete style sheet is shown in [Listing 2.1].

Listing 2.1. A Basic Style Sheet with Color, Size, and Font Declarations
/* basic-2.1.css */
body { font-family: Arial;
color: black;
background-color: white; }

/* I think Verdana looks nice for headlines */
h1, h2, h3, h4, h5, h6
{ font-family: Verdana, sans-serif; }

/* This makes the largest heading have a background */
h1 { background-color: silver; }

/* This puts the even numbered headings in gray */
h2, h4, h6
{ color: gray; }

table { background-color: white; }
th { background-color: black;
color: white;
font-size: smaller; }
td { background-color: gray;
font-size: smaller; }

address { font-family: "Courier New", monospace;
font-size: larger; }


You can find a copy of this style sheet on the book's website.

Linking a Style Sheet to an HTML Page[wax ka badal]

A style sheet by itself doesn't really do anything except sit there on your hard drive or web server. If you try to load it in your browser, it displays as just plain text. To actually use the CSS rules, you need to have a file with markup, such as an HTML page, and you need to add an HTML tag to link the CSS file to the web page.

A Simple HTML Page for Styling[wax ka badal]

[Listing 2.2] shows the structure of a basic HTML page like one you might find on the Web; it has headlines, paragraphs, horizontal rules, and even a table on the side. You can download a copy of this file from the book's website—because that's easier than typing in the whole thing.

Listing 2.2. A Simple HTML File that Needs Styling
<!-- authorbio-2.2.html -->
<html>
<head>
<title>Kynn.com</title>
</head>
<body>
<h1>Kynn.com</h1>
<table align="right" width="25%">
<tr><th><h3>New Stuff</h3></th></tr>
<tr><td>
<ul>
<li>Pictures of <a href="http://www.desertmuseum.org/">
The Arizona-Sonora Desert Museum</a> from
<a href="/gallery/2006/02/desertmuseum/">February
2006</a></li>
<li>The <a href="/projects/heritage-tour/">Black
Heritage Tour of Tucson, Arizona</a></li>
</ul>
</td></tr>
</table>
<h2>Kynn Bartlett's Web Site</h2>
<p>Welcome to my site!</p>
<h3>Biography</h3>
<p>Kynn Bartlett has been using the Internet since
1986, and has been a Web developer since 1994.
Self-taught in HTML, CSS, XML, and many other Web
technologies, he passes this knowledge along to others
through authoring books, teaching online classes, and
giving seminars and presentations. His specialty is
Web accessibility: Making Web sites that can be used
by people with disabilities.</p>
<p>Kynn was a key board member in building the HTML Writers
Guild, a non-profit educational association of Web
developers from around the world, and helped create the
Guild's online education program. He also served as the
Guild's representative on several World Wide Web
Consortium working groups.</p>
<p>From 1995 to 2005, Kynn was the co-owner and Chief
Technologist of Idyll Mountain Internet, in Fullerton,
California. Currently, he lives in Tucson, Arizona, where
he writes books and does digital photography in addition
to Web consulting.</p>
<hr>
<address>
<a href="mailto:kynn@css24.com">kynn@css24.com</a>
</address>
</body>
</html>


As shown in the screenshot in [Figure 2.3], web browsers display this simply, without any CSS styles. It's not ugly, but it's not very interesting to look at, either.

Linked Style Sheets in HTML[wax ka badal]

To apply the style sheet to the HTML page, you need to tell the browser which style sheet to use. You do this by using the <link> element of HTML, and in this case the basic-2.1.css file from [Listing 2.1].

The <link> tag can appear only within the <head> section of the HTML page. To link the style sheet, I open the HTML file and add the following line (shown in bold):

<head>
 <title>Kynn.com</title>
 <link type="text/css" rel="stylesheet" href="basic-2.1.css">
</head>

You can see the effect of applying the style sheet in [Figure 2.4]; compare this with [Figure 2.3] to see the difference CSS can make in the appearance of the page.

Viewing Your Style Sheet[wax ka badal]

After you've created a style sheet, you'll want to take a look at it to ensure that it works. Uneven browser support for CSS means that it's important to check how it appears in various browsers, as well as to make sure you got the syntax correct.

To view the style sheet, simply view the HTML file that links to your CSS file. Don't try viewing the CSS file directly; it just looks like source code in many browsers. The way to know whether it worked is to look at the HTML page that's being styled.

Recommended Browsers[wax ka badal]

You'll want to verify your style sheet in at least the major browsers because they represent the greatest number of users who may access your page. You'll also want to test in browsers that have good support for the CSS standard. Browsers can vary between operating systems; Internet Explorer on Microsoft Windows handles CSS quite differently from Internet Explorer on a Macintosh.

Naturally, it's difficult for one person to have access to every different browser combination available, but the more you're able to use, the better your results will be. I recommend a standard testing suite consisting of three or four of the following browsers:

  • Internet Explorer (6.0 or higher for Windows)
  • Safari (1.3 or higher for Mac OS X)
  • Firefox (1.5 or higher for Windows, Mac OS X, or Linux)
  • Opera (8.5 or higher for Windows, Mac OS X, or Linux)
  • Lynx (2.8 or higher; Windows, Macintosh, or Linux)

These browsers represent a good cross-section for testing, and are generally widely available on most popular operating systems. In [Hour 3] you'll learn more about these browsers and how to install them on your computer.

Try it Yourself: Creating Your First Style Sheet[wax ka badal]

Learning by doing is the key to understanding Cascading Style Sheets, and building your own style sheet is the first step in the process. Follow these instructions to create and test your own CSS:

1. Select an HTML page to style. This could be one you've created before, a brand new one, or perhaps the authorbio-2.2.html file used earlier this hour.

2. Create a new CSS file, using the text editor of your choice. Using the style properties you learned this hour, add style rules to apply to your HTML page. Change the color of the text, the background color, the font sizes, and the text font. Save this file with a .css extension.

3. Use the <link> tag in your HTML to associate the style sheet with the HTML page. Be sure the HTML and CSS files are in the same directory, or else the browser might not be able to find the CSS file. (You can use full URL paths if you want, but for now, it's easiest to have HTML and CSS in the same location.)

4. Open your page in your primary web browser and view the results of your work. You may want to go back and tweak the CSS to see what effect additional styles have; go right ahead, and then reload the page!

5. If you have any of the other recommended browsers, try the page with those. You probably won't see much difference because the CSS properties introduced in this hour are relatively safe and reasonably well supported.

Summary[wax ka badal]

In this hour, you learned about using text editors and specialized software to create and edit style sheets, which are just ordinary text files of CSS rules. You learned the general structure of a CSS rule and its component parts, including the selector, the declaration, the property name, and the property value. You learned how and why to include comments in your CSS files. You got to see a few simple styles change an HTML page, setting the text color, size, and font, and you learned how the HTML <link> tag associates a style sheet with a web page. Finally, you learned how to display your page in your browser and see your CSS in action.

Workshop[wax ka badal]

The workshop contains a Q&A section, quiz questions, and activities to help reinforce what you've learned in this hour. If you get stuck, the answers to the quiz can be found after the questions.

Q&A[wax ka badal]

Q. I'm not sure what the "RGB" values used for colors are. Can you explain?
A. Sure! RGB triples are one of the most common ways to specify color on the Web, in both HTML and CSS. RGB stands for Red-Green-Blue and is a standard way to specify a color as a composite of three values: the amount of red, the amount of green, and the amount of blue. In HTML and CSS these are written in hexadecimal numbers (base 16), which start with 0, go up to 9, and then continue on to A, B, C, D, E, and F. If you don't know how to use RGB hexadecimal values, you can use the rgb() function to specify colors, like this:

h1 { color: rgb(100%, 50%, 25%); }

Q. Can I set the font-size to a specific value, such as 12 point?
A. Yes, you can; 12 point is written as 12pt (no space). This is what's known as an absolute font size, though, and it can cause problems for users who need to adjust their preferences to account for visual impairments. For now I recommend sticking with the relative values given earlier in this hour, like larger and x-small, but if you want you can read ahead to [ch09.html#ch09 Hour 9] for more about font size units.

Quiz[wax ka badal]

1. What kind of software is needed to create a CSS file?
2. What is the name of the part of a CSS rule that goes within the curly braces?
  1. The selector
  2. The declaration
  3. The property name
  4. The property value
3. You want to make all your HTML headings (<h1>, and so on) blue and in Arial font. What CSS rule(s) do you write?

Answers[wax ka badal]

1. Because CSS files are just ordinary text files, anything that can create or edit text files can make a style sheet. This includes text editors, style sheet editors, web development tools, and word processors. The important thing is to save the files as plain text, usually with a .css file extension suffix.
2. The declaration, which consists of the one or more pairs of property names and values, is the part of the CSS rule between curly braces.
3. Here's the easiest way to make headings blue and Arial:
h1, h2, h3, h4, h5, h6
{
color: blue;
font-family: Arial;
}


You could also write this as several rules—as many as 12—but this combined form is the easiest way to do it.

Exercise[wax ka badal]

You now know how to make the easiest types of style sheets—those that can be applied to HTML pages to change the colors, background colors, and fonts of HTML tags on the page. Test your new skills by creating several web pages that use the same style sheet. You will soon notice you're running into some limitations—you have to style all elements the same way. In [Hour 4], "Using CSS with HTML," you'll learn how to expand your repertoire of selectors.