Cascading Style Sheets (CSS)

CSS is a stylesheet language understood by practically every browser on the planet. It can be used to style XML, too. You can't really be a serious web developer without knowing at least the basics of CSS.

Motivation

Remember,

These three items must always be cleanly separated.

You can define different stylesheets for different media: PCs, handhelds, cellphones, speech output devices, print, etc. all differ widely in resolution, color depth, bandwidth, etc.

Quick Facts

CSS is maintained by the W3C and has its own home page. Instead of versions, CSS has levels:

Getting Started

Statements

A CSS style sheet consists of a sequence of statements. Each statement is either a ruleset or an at-rule.

Rulesets

A ruleset is a statement that tells the user agent (UA) how to render an element or elements.

ruleset.png

You can condense rulesets as follows:

Instead of...You can write...
h1 {font-weight: bold}
h2 {font-weight: bold}
h3 (font-weight: bold}
h1, h2, h3 {font-weight: bold}
h1 {color: green}
h1 {text-align: center}
h1 {
  color: green;
  text-align: center;
}

Selectors

See

Properties

There are hundreds of propeties. CSS1 had just few, and CSS2 brought the count up to 100 or so; CSS3 added a bunch.

You might be interested in the W3C's description of all the properties that are officially part of CSS Snapshot 2010.

Of course there are many more properties supported by browsers these days. Here are a sampling of properties, divided up into functional groups:

ModuleProperties
Colorcolor opacity
Backgrounds and Bordersbackground background-attachment background-clip background-color background-image background-origin background-position background-repeat background-size border border-color border-image border-image-outset border-image-repeat border-image-slice border-image-source border-image-width border-radius border-style border-top border-right border-bottom border-left border-top-color border-right-color border-bottom-color border-left-color border-top-right-radius border-bottom-right-radius border-bottom-left-radius border-top-left-radius border-top-style border-right-style border-bottom-style border-left-style border-top-width border-right-width border-bottom-width border-left-width border-width box-decoration-break box-shadow
Multi-column Layoutbreak-after break-before break-inside column-count column-fill column-gap column-rule column-rule-color column-rule-style columns column-span column-width
Marqueemarquee-direction marquee-play-count marquee-speed maruqee-style overflow-style
Texthanging-punctuation hyphenate-characters hyphenate-limit-chars hyphenate-limit-last hyphenate-limit-lines hyphenate-limit-zone hyphens letter-spacing line-break overflow-wrap tab-size text-align text-align-last text-decoration text-decoration-color text-decoration-line text-decoration-skip text-decoration-style text-emphasis text-emphasis-color text-emphasis-position text-emphasis-skip text-emphasis-style text-indent text-justify text-shadow text-space-collapse text-spacing text-transform text-underline-position text-wrap white-space word-break word-spacing
Generated Content for Paged Mediableed bookmark-label bookmark-level bookmark-state bookmark-target float-offset marks string-set
Fontsfont font-family font-feature-settings font-kerning font-language-override font-size font-size-adjust font-stretch font-style font-synthesis font-variant font-variant-alternates font-variant-caps font-variant-east-asian font-variant-ligatures font-variant-numeric font-variant-position font-weight
Basic Box Modelclear display float height margin margin-top margin-right margin-bottom margin-left marquee-direction marquee-loop marquee-speed marquee-style max-width max-height min-width min-height overflow overflow-style overflow-x overflow-y padding padding=top padding-right padding-bottom padding-left rotation rotation-point visibility width
Speechcue cue-after cue-before pause pause-after pause-before rest rest-after rest-before speak speak-as voice-balance voice-duration voice-family voice-pitch voice-range voice-rate voice-stree voice-volume

At-rules

An at-rule is kind of like an instruction to the CSS parser. The common at-rules are:

Examples

Basic Examples

  h1 {
    font-weight: bold;
    font-size: 12pt;
    line-height: 14pt;
    font-family: Helvetica;
    font-variant: normal;
    font-style: normal;
    font-stretch: normal;
    font-size-adjust: none
  }

  h1 { font: bold 12pt/14pt Helvetica }

  ol li {list-style: upper-alpha}
  ol ol li {list-style: upper-roman}
  ol ol ol li {list-style: lower-alpha}
  ol ol ol ol li {list-style: decimal}

Advanced Examples

Miscellaneous non-examples

  p   { font-vendor: any }     /* Invalid prop.: font-vendor */
  h1  { font-style: 12pt }     /* Invalid value for prop: 12pt */
  h1  { rotation: 70minutes }  /* 70minutes is not a valid value */
  img { float: left here }     /* "here" is not a value of 'float' */
  img { background: "red" }    /* keywords cannot be quoted in CSS2 */
  img { border-width: 3 }      /* a unit must be specified for length values */
  h3, h4 & h5 {color: red }    /* & is an invalid token- WHOLE LINE must be ignored */

Connecting a stylesheet to a document

Quite a few ways:

  1. In an XML <?xml-stylesheet?> processing instruction.
  2. In an HTML <link> element.
  3. In an HTML <style> element.
  4. As a style attribute in any HTML element that allows it. (This is called an "inline style". Use rarely if at all.)

xml-stylesheet Processing Instruction

Example (from Harold and Means' text):

<?xml-stylesheet href="recipe.css" media="screen"
           alternate="no" title="For Web Browsers" charset="US-ASCII"?>
<?xml-stylesheet href="printable_recipe.css" media="print"
           alternate="no" title="For Printing" charset="ISO-8859-1"?>
<?xml-stylesheet href="big_recipe.css" media="projection"
           alternate="no" title="For presentations" charset="UTF-8"?>
<?xml-stylesheet href="tty_recipe.css" media="tty"
           alternate="no" title="For Lynx" charset="US-ASCII"?>
<?xml-stylesheet href="small_recipe.css" media="handheld"
           alternate="no" title="For Palm Pilots" charset="US-ASCII"?>

The possible values for media are: screen, tty, tv, projection, handheld, print, braille, aural, all.

The <link> element

Example

<html>
  <head>
    <title>Another Example</title>
    <link rel="stylesheet" href="plain.css" media="screen" />
  </head>
  <body>
    <p>Hello</p>
  </body>
</html>

The <style> element

Example

<html>
  <head>
    <title>Another Example</title>
    <style>
      body {padding: 2em; background: white;}
      p {font: 36pt serif}
    </style>
  </head>
  <body>
    <p>Hello</p>
  </body>
</html>

Inline styles

Use rarely, if at all. Examples:

<h1 style="color:blue; text-align:right">Hello</h1>
<div style="position:absolute; z-index:1; left:20px; top:160px; width:150px">

Inheritance

A property whose value is 'inherit' uses the same value as its parent.

<html>
  <head>
    <title>Another Example</title>
    <style>
      body {color: green; background: white;}
      h1 {color: navy}
    </style>
  </head>
  <body>
    <h1>Test</h1>
    <p>Here is an <strong>example</strong> of</p>
    <ul>
      <li>Style sheets</li>
      <li>Inheritance of properties</li>
      <li>Overriding</li>
    </ul>
  </body>
</html>

cssinheritance.gif

The Cascade

Stylesheets can come from the user agent (browser), the end user, or the author of the document. There may be conflicts. Which one wins?

Here is a nice presentation on the cascade by Russ Weakley:

The CSS Language

Grammar

The actual grammar is in Appendix D of the official spec. In addition to the grammar the spec defines the meanings of the properties and values, what comments look like (/* ... */), where comments and whitespace can go, legal characters, lexical issues like specification of characters with high codepoints, etc.

Sometimes you will see the following metasymbols used in the grammar when definining properties:

A B        - A must occur, followed by B
A | B      - Exactly one of A or B must occur
A || B     - One or more of A or B must occur, in any order

Precedence:
A B | C || D E  means [A B] | [C || [D E]]

Pragmatics

The spec also metions how user agents must treat errors in stylesheets. Some examples:

Types

identifier
integer
number
length         ⇒ ['+' | '-'] number ('em' | 'ex' | 'px' | 'in' | 'cm' | 'pt' | 'pc')
percentage     ⇒ number '%'
uri
color
counter
angle          ⇒ ['+' | '-'] number
time           ⇒ number ('ms' | 's')
frequency
string
border-style   ⇒ ('none' | 'hidden' | 'dotted' | 'dashed'
               | 'solid' | 'double' | 'groove' | 'ridge'
               | 'inset' | 'outset'
border-width   ⇒ 'thin' | 'medium' | 'thick' | length
shape          ⇒
family-name    ⇒ identifier | string
generic-family ⇒ 'serif' | 'sans-serif' | 'cursive' | 'fantasy' | 'monospace'
absolute-size  ⇒ 'xx-small' | 'x-small' | 'small' | 'medium' | 'large'
               | 'x-large' | 'xx-large'
relative-size  ⇒ 'larger' | 'smaller'
margin-width   ⇒ length | percentage | 'auto'
padding-width  ⇒ length | percentage
specific-voice ⇒ identifier
generic-voice  ⇒ 'male' | 'female' | 'child'