CSS

Goals

Concepts

Lesson

A central theme of web development for over a decade has been the separation of content and presentation. HTML5 stresses semantic markup, deprecating elements related to how content looks, and instead stressing the importance of choosing elements that indicate what the content means. But if HTML represents informational content, where does one indicate how that information should be presented to the user?

Cascading Style Sheets

Presentation information such as colors and fonts are referred to as a document's style and is stored in a separate style sheet. The standard approach for describing the style of a web document is called Cascading Style Sheets (CSS), which refers to the language used to create the style sheets. As with HTML5, the World Wide Web Consortium (W3C) creates and publishes the CSS specifications, the latest of which are collectively known as CSS3.

CSS styles are defined by a series of style rules. To give you an idea of what CSS style rules look like, here is a simple rule that makes every first-level heading <h1> element appear in blue, italic text.

Simple CSS style rule.
/* Make first-level headers blue italic. */
h1 {
  color: blue;
  font-style: italic;
}

A style rule consists of several parts:

selector
In the example the h1 part is called a selector because it “selects” which elements in the document the style should be applied to.
property
The tokens color and font-style are properties you want to change for the selected element(s).
value
Here blue and italic are the values you want to set for the indicated properties.
comment
Comments are optional and use the same /* … */ format as multiline comments in Java.

Common Properties

CSS provides properties for manipulating fonts, colors, borders, and positions, as a start. You'll learn to use many more CSS properties in the lessons ahead, but here are a few of the most common and straightforward properties so that you can start using CSS right away. For an idea of the full set of CSS properties in the various levels, see the W3C's List of CSS properties, both proposed and standard.

color
Specifies the color of the text. See Colors below. You might think of this as the “foreground color” property, as there are other properties for specifying the color of things besides the text, such as backgrounds and borders.
font-family
Specifies the font to use, a comma-separated list of font names in order of preference. If a font name contains a space, put the name in quotes. See Fonts below.
font-style
Indicates whether the font is italic. Allowable values are normal, italic, and oblique.
font-weight
Specifies the boldness of the font. Although value can be a numeric multiple of 100 between 100 (“Thin”) and 900 (“Heavy”), CSS also allows weight names that may make your style sheet more understandable: normal (equivalent to 400), bold (equivalent to 700), bolder (bolder than the font would normally be), and lighter (lighter than the font would normally be).
font-size
Indicates how large the font should be. There are many ways to specify the value, including the relative sizes larger and smaller, or a percentage such as 120%, calculated in relation to the parent element's font size. In a future lesson you will learn how to use an em value to specify a size that will be calculated based upon the other font sizes. Although CSS allows you to specify an absolute size or an absolute length value (such as as pixels or points), this unnecessarily restricts your styles and prevent your font from scaling appropriately on various devices and if viewing options are changed.
background-color
Specifies the color for the background behind the text. See Colors below.
background-image
TODO

Colors

RGB additive color
RGB additive color 
(Wikimedia Commons)

Most computer displays generate a specific color conceptually by mixing varying amounts of red, green, and blue. These three “channels” make up the the RGB color model. In CSS a color value can be specified using the form rgb(red, green, blue), where the individual color components are specified either as a value between 0 – 255, or a percentage representing the same range.

In the RGB color model, rgb(0, 0, 0) refers to black, while rgb(255, 255, 255) and  rgb(100%, 100%, 100%) both refer to white. Pure red uses only the first channel, rgb(100%, 0, 0), while yellow mixes red and green, resulting in rgb(255, 255, 0).

You can also represent RGB values using a six-digit hexadecimal representation beginning with the pound # sign, with each two digits representing red, green, and blue in the form #rrggbb. Thus #000000 is black, #FFFFFF is white, #FF0000 is red, and #FFFF00 is yellow. CSS values are case-insensitive. You can also represent each channel as an eight-bit value, resulting in a three-digit hex number in which yellow is #FF0 for example.

Alpha

CSS also permits an additional alpha channel, which can be represented as rgb(red, green, blue, alpha). There is no hexadecimal representation for alpha values. The alpha channel represents opacity, for which 0% makes the color completely transparent (i.e. see-through) and 100% makes the color fully opaque.

HSL
Hue scale
Hue scale, 0°–360°
(Wikimedia Commons)

RGB colors can also be represented by three values representing hue, saturation and lightness (HSL). The hue is represented by the angle the rainbow as a color circle, while saturation and lightness are given in percentages, for which 100% is full saturation and 50% is normal lightness. CSS provides both hsl(hue, saturation, lightness) and hsla(hue, saturation, lightness, alpha) representations for indicating colors using HSL. In this schema hsl(0, 100%, 50%) indicates the same red color as rgb(100%, 0, 0). You may find HSL representation more intuitive, as it allows you to start with a specific hue instead of thinking about mixing colors.

Indicating the color “aqua”.
Keywords

Lastly CSS provides a set of keywords that represent common colors. The most common colors are present, including black (#000000), white (#FFFFFF), red (#FF0000), and yellow (#FFFF00). The 16 basic CSS colors aqua, black, blue, fuchsia, gray, green, lime, maroon, navy, olive, purple, red, silver, teal, white, and yellow were later supplemented by a longer list in later levels of the specification. For a complete list and more in-depth discussion, see Mozilla's <color> page.

Fonts

When designing a page, web designers may have a specific font in mind that exactly communicates the feel and matches the surrounding content. But not every font is available on every system. CSS allows a style rule to provide a list of fonts, with the preferred font appearing first in the list; the other fonts provide “fallback” alternatives if the preferred font is not available.

CSS provides several general generic families that are expected to available on most system. They do not indicate particular font families, but rather general categories of font appearance. These generic families are serif, sans-serif, cursive, fantasy, and monospace. You should always include a generic family at the end if your font-family value list.

Including Styles

Browser Style Sheets

Styles are so easy to include that you get a style sheet for free just by viewing your HTML page. Each browser, which the CSS specifications refer to as a user agent, comes with its own built-in set of styles. That is why normally the <em> element is shown in italics, and heading elements such as <h1> appear larger than the other text, with no further work necessary.

External Style Sheets

The best practice is to place style rules into an external style sheet. This makes explicit the separation of content and presentation, and allows a single style sheet to be applied to multiple HTML documents. A CSS style sheet has the media type text/css, and when stored in a file usually has a css extension.

Linking to an external style sheet.
<!DOCTYPE html>
<html lang="en-US">
<head>
  <title>HTML Skeleton</title>
  <link href="styles.css" rel="stylesheet"/>
</head>
…

An HTML document indicates an an external style sheet by using the <link> element inside the <head> section of the web page. The <link> element uses the href attribute to indicate the URL of the style sheet to load. You might recall the href attribute for the <a> element, which works in the same way.

Also similar to the <a> element, <link> has a rel attribute; you must set it to the value stylesheet to indicate that linked document serves as the style sheet of the page. There is also a type attribute which you may set to the media type of the stylesheet, that is type="text/css". With HTML5 the type attribute is now optional, because CSS is the default type (and virtually the only type) of style sheet used in modern web pages.

Internal Style Sheets

Internal style sheet.
<!DOCTYPE html>
<html lang="en-US">
<head>
  <title>HTML Skeleton</title>
  <style>
  h1 {
    color: blue;
    font-style: italic;
  }
  </style>
</head>
…

You can also place CSS style rules directly into the HTML document using the <style> element inside the <head> section. This prevents you from using the styles with other documents, however. Try not to use internal style sheets, as they tie the style definitions closely to your content. As with <link> the <style> type attribute is optional and defaults to text/css.

Inline Styles

HTML allows you to assign a style attribute to any element, containing the contents of a style rule to apply to that element. For example you could make a single <h1> element appear using blue, italic text using <h1 style="color: blue; font-style: italic">. Inline styles are extremely bad practice. They literally places style information in the markup of the document, defeating any attempt to separate content and presentation.

User Styles

The various sources can be categorized based upon originating role. Browser styles are classified as user agent declarations. External, internal, and inline styles are are categories as author declarations, because they are provided by the author of the style sheet. In addition browsers allow users to provide custom overrides at the application level; these are called user declarations.

Selectors

Each of the style rules in your style sheet(s) will include at least one selector, which indicates to which elements in your document the rule should be applied. A selector is analogous to a regular expression, although the rules are tailored to elements in an HTML document rather than characters in a string. See Selectors Level 4.

Type Selectors

Type selectors.
h1, em {
  color: blue;
}

The most basic selector is a type selector. A better name might be “element selector”, because these indicate simply the name (the “type”) of the element to style. A type selector appeared in the first example in this lesson. See Selectors Level 4 § 5.1. Type (tag name) selector.

As with all style rules, you can provide multiple selectors by separating them with commas. The example in the figure indicates that the contents of every first-level heading, as well as all emphasized text, should be displayed in blue.

Pseudo-Elements

CSS allows you to style “things” in a document that don't necessarily have an element available for styling. Such a pseudo-element begins with two colon :: characters, and you can combine pseudo-elements with with type selectors. The following CSS would show the first line of every paragraph in italics.

p::first-line {
  font-style: italic;
}

Universal Selector

A special selector uses the asterisk * character in place of the element name. This universal selector is similar to a regular expression or glob wildcard, and matches every single element on the page. See Selectors Level 4 § 5.2. Universal selector.

Class Selectors

Class selectors.
<p>Class selectors are very common.</p>
<p class="hint">You can use class
  selectors with or without an
  element name.</p>
.hint {
  color: green;
}

HTML provides a special class attribute which, as a global attribute, can be placed on any element in the document. This attribute allows you to “classify” elements by organizing them into categories. See Selectors Level 4 § 6.6. Class selectors.

With the CSS class selector you indicate the class name to match after the full stop . character. The class selector can be used in two ways. The following explanation use the example HTML in the figure.

p.hint
A compound selector (a selector made up of a type selector and one or more other selectors) selecting only <p> elements that have a class attribute with the value "hint".
.hint
Selects all elements that each have a class attribute with the value "hint". This form is really a compound selector as well; the universal selector is implied.
Multiple Classes

An HTML class attribute can contain more than one class name, separated by whitespace. This allows elements to be classified at a detailed level. You can then select specific combinations of classifiers by adding additional class selectors, still using the full stop . character as a separator.

Consider a paragraph with the following classes: <p class="intro hint favorite">. A CSS style rule with the selector p.favorite.hint would match all paragraphs marked with the classes hint and favorite, whether or not they were intro paragraphs as well.

Pseudo-Classes

While a pseudo-element selects content that may not provide an element for selection, a pseudo-class selects content based upon some aspect or state. A pseudo-class begins with a single colon : character.

Some of the most-used pseudo-classes relate to links. For example the :hover peudo-class represents an element that the mouse is currently hovering over. The following example combines this pseudo-class with a selector for the <a> element. The rule changes the color of a hyperlink to red, but only when the mouse cursor is positioned over the link.

a:hover {
  color: red;
}

ID Selectors

HTML ID attribute.
<p id="summary">CSS provides many types
  of selectors to use.</p>
#summary {
  color: purple;
}

Another type of selector made for a specific HTML attribute is the ID selector, which as the name implies selects elements based upon the HTML id attribute. Indicate the ID to match using a number sign # character before the ID value. For example, a selector of #summary would match the summary paragraph in the example in the figure. See Selectors Level 4 § 6.7. ID selectors.

Attribute Selectors

In addition to selecting elements with certain class and ID attributes, CSS allows selecting elements by arbitrary attribute values. The most straightforward form of an attribute selector is [foo=bar], which selects all elements containing an attribute named foo with a value of "bar",  such as <div foo="bar">. The latest CSS recommendations provide many other variations. See Selectors Level 4 § 6. Attribute selectors.

[foo]
Selects all elements that contains the attribute foo, regardless of its value.
[foo=bar]
Selects all elements with a foo attribute with exactly the value "bar".
[foo~=bar]
Selects elements with a foo attribute containing a whitespace-separated list of words, one of which is "bar". Note that this is exactly how class selectors work.
[foo|=bar]
Selects elements with a foo attribute with the value "bar" or starting with "bar-". This selector was specifically created to match language tags. A selector of p[lang|="pt"] would apply to all paragraphs marked as written in Portuguese, matching both <p lang="pt"> and <p lang="pt-BR">, for example.
[foo^=bar]
Selects elements with a foo attribute beginning with "val". Recall the regular expression start of line anchor.
[foo$=bar]
Selects elements with a foo attribute ending with "val". Recall the regular expression end of line anchor.
[foo*=bar]
Selects elements with a foo attribute containing "bar" as a substring.

Complex Selectors

CSS selectors are individually useful, and they become even more powerful when you combine several of them in a row. A complex selector is a series of compound selectors separated joined by some combinator punctuation. See Selectors Level 4 § 13. Combinators.

To see how complex selectors work, consider the following excerpt from the XHTML source code of the lesson on inheritance:

<h4>Super Methods</h4>
<p>Sometimes a <a href="#subclass">subclass</a> doesn't want to replace functionality altogether
  —it may want merely to add to the existing functionality of a super class. A subclass is therefore allowed to invoke
  the super class version of a function before, during, or after the specialized version. Take for example a
  <a class="external" href="https://en.wikipedia.org/wiki/Fire_engine#Tiller_truck">“tiller truck”</a>,
  a type of	fire engine that has separate drivers for the front and rear sets of wheels.</p>
<figure>
  <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/e/eb/Lafd_ladder_truck.jpg/800px-Lafd_ladder_truck.jpg"
    alt="Tiller truck fire engine." />
  <p><em>You may want to see the <a class="external" href="https://upload.wikimedia.org/wikipedia/commons/e/eb/Lafd_ladder_truck.jpg">
    full-sized version</a>.</em></p>
  <figcaption>
    Tiller or “hook-and-ladder” truck fire engine.
    (<a class="external" href="https://commons.wikimedia.org/wiki/File:Lafd_ladder_truck.jpg">Wikimedia Commons</a>)
  </figcaption>
</figure>
Descendant Combinator

Perhaps the most common combinator is the descendant combinator, which is simply whitespace. When two selectors are separated by whitespace as in foo bar, it selects all bar elements that are descendants of foo in the HTML document hierarchy. The following style for example would make the hyperlinks in the above figure appear in blue.

figure a {
  color: blue;
}
Child Combinator

The child combinator is the greater-than > symbol, and selects a direct child of another element. The complex selector foo > bar would select only bar elements that were direct children of foo. For example, the following style rule would only select a link that is a direct child of a paragraph <p> element.

p > a {
  color: orange;
}

Additional combinators may be found in the Summary section.

Cascading

With so many potential sources of styles to be applied to your document, it's likely that several rules could indicate conflicting style values. CSS provides rules for resolving style conflicts by defining a set of priority levels called the cascade. This cascade is so essential that the very name “Cascading Style Sheets” refers to it.

The cascade is based upon where the styles originated. In addition, individual style rules can override the default cascade by including the !important annotation after the value, as in color: blue !important. The following is an abridged order of cascade priority, from highest to lowest. See CSS Cascading and Inheritance Level 3 § 6. Cascading.

  1. !important user agent declarations.
  2. !important user declarations.
  3. !important author declarations.
  4. Author declarations.
  5. User declarations.
  6. User agent declarations.

Specificity

At each level of the cascade, CSS provides additional specificity rules for further resolving conflicts. There might be several style sheets from different libraries providing styles for the same elements, or even the same author might intentionally provide “conflicting” selectors in order to style elements differently based on where they appear in the document.

CSS specificity rules involve assigning values to a selector, based upon the location of the rule and which types of selectors are present, and then adding these numbers together. The style rule with the highest number wins. For example ID selectors are assigned higher specificity values than class selectors. The universal selector * is assigned value of zero.

The actual specificity calculation rules are somewhat complex, but below is the general order of priority, from highest to lowest. See Selectors Level 4 § 15. Calculating a selector's specificity.

  1. Inline styles (override everything)
  2. ID selectors.
  3. Class selectors.
  4. Type selectors.
  5. Order of definition (last style wins).

Inheritance

In addition to elements you've explicitly selected for styling, inheritance provides additional styling power by allowing the applied styles of an element to “trickle down” to its children. This is often the best approach for defining a default style for all or part of your document, allowing additional styles to override values for specific child elements.

Let's say that you wanted all the text in a document to appear in blue. There would seem to be three approaches available:

Universal Selector
* {
  color: blue;
}
Type Selector
p, h1, h2, h3, em, strong, … {
  color: blue;
}
Inheritance
body {
  color: blue;
}

The most flexible of these approaches is probably inheritance. The rule specifies that the text of the root element of the document should be blue, yet if no overriding styles are specified, the color style will be inherited by child elements such as <p>, and <h1> as well.

Review

Summary

Selectors
Pattern Name Description Level
* universal selector Selects all elements. 2
E type selector Selects all elements with name E. 1
E.foo class selector Selects E elements with the "foo" as one of the classes. 1
E#foo ID selector Selects the E with an id attribute of "foo". 1
Attribute Selectors
E[foo] Selects all elements that contains the attribute foo, regardless of its value. 2
E[foo=bar] Selects all elements with a foo attribute with exactly the value "bar". 2
E[foo~=bar] Selects elements with a foo attribute containing a whitespace-separated list of words, one of which is "bar". 2
E[foo|=bar] Selects elements with a foo attribute with the value "bar" or starting with "bar-". 2
E[foo^=bar] Selects elements with a foo attribute beginning with "val". 3
E[foo$=bar] Selects elements with a foo attribute ending with "val". 3
E[foo*=bar] Selects elements with a foo attribute containing "bar" as a substring. 3
Complex Selectors
E F descendant combinator Selects an F element that is a descendant of an E element. 1
E > F child combinator Selects an F element that is a direct child of an E element. 2
E ~ F following-sibling combinator Selects an F element preceded by an E element at the same level in the hierarchy. 3
E + F next-sibling combinator Selects an F element immediately preceded by an E element at the same level in the hierarchy. 2

Gotchas

In the Real World

Think About It

Self Evaluation

Task

Add style to the Booker site.

See Also

References

Resources

Acknowledgments