CSS Fundamentals

Rating: 
Body: 

This article is excerpted from Speaking in Styles: Fundamentals of CSS for Web Designers by Jason Cranford Teague. Copyright © 2009. Used with permission of Pearson Education, Inc. and New Riders.

Syntax is how you put words together to create meaning: Punctuation and parts of speech are placed in a specific order to describe something. How you combine these elements has a direct effect on the meaning of what you are trying to communicate.

To describe your Web designs, you need to understand the syntax of CSS.

Although CSS syntax is relatively simple compared to the syntax of a language such as English, it is also less forgiving of mistakes. A misplaced comma or semicolon might change your styles completely or might even turn your styles into incomprehensible gibberish, at least to the browser. But once you get the hang of it, you’ll be speaking in CSS in no time.

The Rules of Style
Web pages are created using HTML tags to add structure to the page. Most of these tags have inherent styles—that is, styles that the browser manufacturer has set as the default. If we left it to the browser to style our pages, they would all look pretty much the same, and none too interesting. CSS acts on the HTML tags telling them how they should appear when rendered on the screen. To change a tag’s style, you create CSS rules that bind styles to particular elements on the screen, either directly to a specific HTML tag or using a class or ID that can then be applied to any HTML tag you desire.

Let’s keep it simple for now, and start by looking at how we create a basic style for the header level 1 HTML tag <h1>. CSS rules begin with a selector, which is what is being defined, followed by a declaration or list of declarations between curly brackets to define the selector’s style.

Independent Canadian hip hop magazine UGSMAG speaks to its audience with a unique visual voice created with CSS.

Parts of a Style Rule
A CSS rule has the equivalents of the subject, object, verb, and adjective that you would find in any English sentence:

  • The subject (what we are describing) is the selector.
  • The object (what is being described about the subject) is the property.
  • The verb (always the verb “to be” in CSS) is represented by a colon.
  • The adjective (the description) is the value.

A Basic Style Rule
To tell another person that you want a level 1 header to be red, you might say something like:

The level 1 header’s text color is red.

In CSS, to communicate the exact same thing, you could say:

h1 { color: red }

In this case, color refers to the text color and red is a predefined keyword that the browser translates into an actual color value. We could also use the RGB scale:

h1 { color: rgb(255,0,0) }

Or the hexadecimal color scale:

h1 { color: #ff0000 }

These all say the same thing: The first-level header’s text color is red. In English this is called a declarative sentence. In CSS this is called a CSS rule or selector declaration.

You are declaring style properties for the selector, in this case the h1 selector, which effects the <h1> tag. There are three types of selectors in CSS. The one shown here is an HTML selector because it corresponds to a specific HTML tag. We will learn about class and ID selectors a bit later in this chapter.

Declaring More Styles
To add multiple declarations to your rule, separate each by a semicolon. You can have one, two, ten, one hundred, or however many declarations you want in a single rule, as long as you separate each by a semicolon, just like you might use a comma or semicolon to separate the items in a sentence:

The level 1 header’s color is red, the font family is Georgia, and the font size is 24px.

To say the same thing in CSS, you list the declarations:

h1 { color: red; font-family: Georgia; font-size: 24px; }

Notice that I’ve put a semicolon after each declaration, including the last one. In the previous example, where there was only one declaration, I didn’t add a semicolon because you don’t have to put a semicolon after the last declaration in a list; you could just leave it off. Now, forget you ever read that:

Always put a semicolon after every declaration in your list, even the last one.

Why? Because one day you will make a change to that CSS rule. You will add another declaration at the end of the list and you will forget to add the semicolon to the previous line, and your style will simply stop working. You will spend hours trying to figure out why your styles are not working only to discover it was because you forgot to add one stupid semicolon. How do I know this? I have spent far too many hours of my life banging my head against my keyboard trying to figure out why my styles aren’t working, all because of a missing semicolon. Learn from my mistakes: Always include the semicolon after every declaration.

Combining Rules
What happens when the same styles are being applied to different selectors? For example, what if you want all of your headers to be red? You could create three different style rules, one for each header level:

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

When speaking, though, you wouldn’t say:

The level 1 header’s text color is red.The level 2 header’s text color is red.The level 3 header’s text color is red.

Instead, you would combine these into a single sentence using commas:

The level 1, level 2, and level 3 header’s text color is red.

Similarly, you can apply the same style declarations to multiple selectors in the same rule by putting them into a comma separated
list:

h1, h2, h3 { color: red; }

Now the first three header levels will be red. Besides saving a lot of space, which is important once your CSS files start getting large, this also has the advantage of putting all of the selectors that use this value into a single place, making it easier to change later. For example, if your boss or client decides they want green headers instead of red, rather than changing the value in three places, you only have to change it once:

h1, h2, h3 { color: green; }Types of Selectors
So far, you’ve only seen one kind of selector: the HTML selector. This allows you to specify how any HTML tag on the page should be styled. If all you could do was style HTML tags and all of the paragraphs looked the same, and all of the level 2 headers looked the same, and all of the lists looked the same, and so forth, your designs would look pretty boring. You need ways to selectively style HTML tags with CSS.

For example, you might have your level 2 headers look one way when in the main text of an article, another in the sidebar, and yet a third when used as the caption for a photo.

CSS provides three distinct selector types that enable you to tailor your design to appear exactly the way you want.

HTML Selector
To define how a particular HTML tag should be styled indiscriminately across your Web page, use its HTML selector. For example, if you say that all header level 2 tags should be red:

The level 2 header’s text color is red.h2 { color: red; }

The styles will be applied to any content tagged with:

<h2>...</h2>

All header level 2 tags on the page will be red, unless you override its declarations with other declarations. More about that later.

Class Selector
If you don’t want all of your tags to appear exactly the same, you need a “free agent” selector that can be applied to any HTML tag. This is the class selector. When defining a class rule, you place a period immediately before the class name to let the browser know, “Hey, this is a class selector, not an HTML or ID selector”:

.hilight { background-color: yellow;}

This says:

The hilight class text background color is yellow.

To apply this class (and thus its styles) to an HTML tag, add the class attribute to a tag with the class name in quotes. You can apply the same class to any HTML tag you choose, as many times as you want:

<h2 class=“hilight”>Chapter I...</h2>

Notice though that you do not add the period with the class name when it’s in the HTML tag. The period is only included when you are setting up the class rule.

Class Selector: Dependent Class
A dependent class allows you to specify the styles a class should have if the class is applied to a particular HTML tag. This allows you to create a general style for a class, but then specify more styles for a specific HTML tag within that class. For example, you might set up a general class to make the background color yellow, and then set up a dependent class so that when that class is applied to a particular tag, the background color is green instead:

If the hilight class is used with a level 2 header, then its background color is green.h2.hilight { background-color: green; }Class Selector: Mix and Match Classes
As if being able to add a single class to an HTML tag wasn’t enough, you can also add multiple classes to a single HTML tag, mixing and matching styles as needed. Simply list all of the classes you want applied to a particular HTML tag in the class attribute, separated by spaces:

<p class=“hilight smallprint”>'I should...</p>

When applied to an HTML tag, that tag picks up the styles of all of the classes applied to it.

You can call your classes or IDs anything you want as long as you follow these basic rules:

  • It can start with a letter or a number.
  • It can contain any letter, number, hyphen (“-”), or underscore (“_”).
  • Both classes and IDs are case sensitive. So, “myClassName” is different from “myclassname”.

Class or ID names could be “bob”, “3423_jyt”, or “9-8-2009”, but you should always try to name them something meaningful according to what the class or ID is for, rather than what styles it applies. For example, I might call a class “redText” to hilight certain text. But what happens if later I want to make the hilighted text yellow? The yellow text is now created using a class called redText. A better choice would be to call the class something like “hilight” or “smallprint,” which describes what it is for and allows for different versions.

ID Selector
The first thing to know about the ID selector is that, on the surface at least, it looks and acts exactly like the class selector. The only obvious difference is that you use a hash mark at the beginning, to declare it, rather than a period:

#title01 { color: green; }

To apply the ID (and thus its styles) to an HTML tag, add the ID attribute to the tag with the name of the ID you want to apply:

<div id=“title01”>Chapter I...</div>

Similar to the class selector, you do not add the hash mark with the ID name when it’s in the HTML tag. The hash mark is only included when you are setting up the ID rule.

So what’s the difference between a class and an ID? It isn’t so much in how these selectors work, but in what you use them for:

  • Identifying major page sections (for example, header, content, footer)
  • Identifying unique content or modules (for example, search, navigation, ad)
  • Identifying an element to be used with Javascript
  • Specificity, which we will talk about more in the next chapter

Styles in Context
When speaking, context can radically alter the meaning of a statement. Take the phrase:

“I’m going to kill you!”

If someone said that while whacking you on the head with a pillow, it would mean something very different than if they said it while whacking you on the head with a baseball bat. The context in which those words are spoken is the difference between the phrase being a playful euphemism or a menacing threat.

Likewise, in CSS, the context of a particular element can determine its style. For example, if you want headers in a sidebar to look different from headers in the main body, you can easily give each a different look by defining how the level 1 header tag should look in the body and a different rule for how it should look in a sidebar.

Styles Based on Where Something Is
The most frequent way to use context is to style an element based on the HTML tags, classes, or IDs of its parent elements. Remember that an element is created anytime you put HTML tags around content. You can nest one element inside of another, and the surrounding tags are called parent elements. We can then write our CSS to style a tag based on the HTML tags, classes, or IDs that the element is within to style the descendent selectors.

A Simple Example of Descendent Selector Context
For example, you might style the text color <cite> tag—which is used to indicate that a block of text is a citation, such as a book title like Through the Looking-Glass—green, but make it red if it’s in a level 1 header. To do this, we list each of the selectors that define the context, with a space in between:

A citation’s text color is green.cite { color: green; }If a citation is in a level 1 header, its text color is red.h1 cite { color: red; }A More Complex Example of Descendent Selector Context
Context is not just for HTML tags. You can get as specific as you want about the context using classes and IDs as well. For example, we might create a rule for a <cite> tag if it’s in the introduction of the article section of the page:

If a citation is in a paragraph with the intro class that is within the article ID, its text color is red.#article p.intro cite { color: red; }

You can create contexts as specific as you like, but keep in mind it is always the last selector in the list that gets the actual styling.

The above CSS would apply its styles to the following content:

<div id=“article”><p class=“intro”><cite>
Through the Looking-Glass
</cite></p></div>

But not to:

<div id=“article”><h1><cite>
Through the Looking-Glass
</cite></h1><div>

Because it doesn’t have the intro class in a paragraph.

Styles for Children
Styles can also discriminate between an element that is a direct child of its parent or an element that is a “grandchild,” allowing you to style child selectors. For example, you can create a rule to make the text red only when it’s the direct child (not a grandchild) of a paragraph tag.

If the emphasis tag is in a paragraph, and does not have any other parent tags, its color is red.p>em { color: red; }

If we applied these two rules to the following HTML code:

<p><em>the white kitten</em><p>

Here, “the white kitten” will be red because the emphasis tag is a directly within the paragraph. However, if we applied it to this HTML code:

<p><strong><em>the old cat</em></strong></p>

In this case, “old cat” would not get the red styling because the strong text is the emphasized text’s direct parent, not the paragraph.

Although IE7 and above rectifies the situation, IE6 does not support styling of child and sibling selectors. Make sure when using these contextual selector types that they are only used as a design enhancement or include a work-around for IE6 as described in Chapter 12, “The Last Word: Dealing with Browser Inconsistencies.”

Styles for Siblings
If elements are next to each other (not nested inside of each other), they are called adjacent or sibling selectors. You can set a style based on an element’s sibling. For example, let’s say you want any citation that’s next to emphasized text to be red:

If a citation is next to emphasized text, its text color is red.em+cite { color: red; }

If we applied this to the following HTML:

<em>Quotes</em> from <cite>Through the Looking-Glass</cite>

The words “Thorough the Looking-Glass” would be red, because the <em> and <cite> tags are next to each other (despite the intervening text).

However, with the following HTML:

<em>Quotes</em> <strong>from</strong>
<cite>Through the Looking-Glass</cite>

The words “Through the Looking-Glass” would not get the red styling because the <strong> tag is in the way.

Styles for Special Cases
Although primarily intended to add styles to particular elements created using HTML tags, there are several cases where we can use CSS to style content on the page that is not specifically set off by HTML tags or to create a dynamic style in reaction to something that your Web site visitor is doing on the screen. These are known as pseudo-elements and pseudo-classes:

  • Link pseudo-classes: Used to style hypertext links. Although primarily associated with color, you can actually use any CSS property to set off
    links and provide user feedback during interaction.
  • Dynamic pseudo-classes: Used to style any element on the screen depending on how the user is interacting with it.
  • Pseudo-elements: Used to style the first letter or first line in a block of text.

Link States
All hypertext links have four “states” that can be styled in reaction to a user action:

  • a link state when there has been no action
  • a hover state when the mouse cursor is over it
  • an active state when the user clicks it
  • a visited state when the user returns after having visited the linked-to page

Styles for Link Actions
Although the link tag can be styled just like any other HTML tag, it is a special case, because people visiting your site can interact with it. It’s a good practice to create different styles to react to what the visitor is doing. To that end, CSS includes four different pseudo-classes for each of the four interaction states: link, visited, hover, and active:

The default link text color is red.a:link { color: red; }If the link is in the browser history, its text color is dark red.a:visited { color: darkred; }When the visitor hovers over a link, its text color is hot pink.a:hover { color: hotpink; }When the visitor clicks a link, its text color is fuchsia.a:active { color: fuchsia; }

Collectively, these are known as the link pseudo-classes. They need to be in the above order—link, visited, hover, active—to function properly, due to the cascade order, which we’ll learn more about in the next chapter. It’s also important to remember that, while links are typically associated with color, any style can be applied to a link.

In Chapter 10, “Navigation” we’ll double down on how to use the link and dynamic pseudo-classes to create a variety of interactive styles for buttons and other controls. It’s important for you to expand your notion of Web site design to include the interactive elements. Often I see visual comps from designers that look great but are static. Don’t ignore the fact that people are usin your site.

Styles for Dynamic Actions
The hover and active states are not just for links. You can actually place your cursor over and click on any element on the screen and style elements for those actions. The third action state is when the user selects an element on the screen (usually a form field) and that element is in focus and it is ready for user input.

The default text color for the class formField in an input box is gray.input.formField { color: gray; }When the user hovers over an input field with the formField class, its text color is green.input.formField:hover { color: green; }When the user clicks an input field with the formField class, its text color is red.input.formField:active { color: red; }While the user is typing in an input field with the formField class, its text color is black.input.formField:focus { color: black; }

Collectively these are called the dynamic pseudo-classes, which allow you to provide interactive feedback to the user. Dynamic pseudo-classes can be applied to any element on the screen but are chiefly used to add dynamic interaction to form fields and buttons, which we will look at in Chapter 10, “Navigation& UI”

One drawback: IE7 does not support active and focus, and IE6 supports none of these.

Liked This? Read These!

DesignMentor Training adds Dr. Taz Tally to their highly respected list of professional design instructors. Tally has developed a challenging and detailed 6-lesson class which covers every aspect of... Read More
Excerpted from "Real World QuarkXPress 5" (Peachpit Press). Read More
Tiny hand-held scanner and app allows you to accurately capture colors wherever you go and use them in a variety of ways. Read More
Anyone familiar with a box of crayons can describe the color "carnation pink" but how many people can make that color appear "correctly" on a document or on a computer display? Read More