NoteLinks Consulting
  1. Home
  2. Services
  3. Resources

This page is intended as a "cheat sheet" for those who have already been exposed to CSS.  We highly recommend reading Eric A. Meyer's CSS Web Site Design (New Jersey: Prentice Hall, 2008) if you are new to CSS.

See also the "CSS" section of the Definitions page.


Basics

Styles

In-line

  • Overrides all other styles
  • For one-off styling only; does not separate style from structure or presentation from content
  • Written as an attribute of the element you are styling; e.g: <p "style="font-size: 20pt; color: #6666ff""> ... </p>

Embedded

  • Will apply only to that page rather than to the whole site
  • Entire CSS document is embedded in XHTML's head section
  • Code generators (e.g. Expression Web, Dreamweaver) create
    embedded style sheets if styles are applied in Design mode.
  • In high-traffic situations such as eBay or Yahoo, this is actually the faster-loading option.
  • More than one style sheet may be embedded (e.g., one for screen and one for print);
    simply use two style elements, one after the other, with different media types.

External (also called "linked")

  • Can apply to entire site
  • Reduces load time and bandwidth usage because it is downloaded once,
    is stored by the browser, and is applied to all pages that call it.
  • Link is placed in document's head section.
  • Example: <link rel="stylesheet" type="text/css" href="shell.css" media="all" />
    • rel
      • Stands for "relationship" (in this case, the linked document is a style sheet).
      • rel="stylesheet": stylesheet must be all one word (no space).
    • For definition of type, href, and media, see "Style Element" below.
  • Link is a feature of XHTML; you can only link from with an XHTML document
    (by contrast, @import is a feature of CSS that allows style sheets to import other style sheets).
  • By linking, you can define sets of style sheets or alternate style sheets for developing "skins".

Imported

  • @import is a CSS directive (not a selector-value pair).
  • A style sheet can have one or more @import directives.
  • Form:
        <head>
        <title> ... </title>
        <style type="text/css" media="all">;
        @import url(resourcePages/resources.css);
        </style>
        </head>
  • The contents of an external style sheet are imported into the document, but are not visible or
    editable as they would be if embedded.
  • The @import directives must be the first code in any style sheet.
  • The @import directives should precede any page-specific styles added to the head section.
  • Theoretically you could import one style sheet for screen, one for print, etc. -- but IE6 and prior
    versions do not support media descriptors
    , so both style sheets would load under these browsers.
  • Not all browsers (including IE) cache imported style sheets -- so you may be forcing more downloads for your users.
  • It is much harder to script imports than to script links, so avoid imports if style sheets are to be switched on and off.
  • You cannot define sets of style sheets, or define alternate style sheets, unless they are linked.

Style Element

Form

: <style type="text/css" href="shell.css" media="all">  </style>  
  • type attribute: specifies the MIME (Multipurpose Internet Mail Extension)
    type that describes a file's content (in this case, a CSS file type).
  • href: stands for Hypertext Reference. In this case,
    it specifies a link to a file called "shell.css".
  • media attribute: allows a page to be styled differently for different
    media (e.g., print, handheld, etc.). In this case, the page is styled the
    same for all media.

Rules

Form

: h1 {font-family: Ariel, Helvetica, sans-serif;}
  • Selector:
    • In this case, h1 (header 1) will be styled as Ariel, Helvetica, or sans-serif.
    • Can style more than one selector at a time: h1, em {font-weight: bold;}
  • Attribute:
    • In this case, font-family
  • Value(s):
    • In this case, Ariel, Helvetica, sans-serif
  • Spaces matter!
    • h1 .red means "Select every element with class of "red" that descends from an "h1" element."
    • h1.red means "Select only h1 elements with a class of "red".

Cascade

  • Often confused with inheritance.
  • Actually, it is a set of conflict resolution mechanisms in which inheritance has the least impact (see "Conflicting Styles", below).

Conflicting Styles

  (resolution mechanisms, from highest to lowest in precedence):

Styles

  • Author styles
  • User (reader) styles
    • For IE7 in Windows,
      • Internet Options/General tab/Accessibility button/User Style Sheet section
      • Check "Format documents using my style sheet"
      • Type the location of the user style sheet
      • Click "OK"
    • User's styles for Firefox:
  • Browser (user agent) styles

Specificity

:
  • !important declaration:
    • Overrides all unimportant declarations, no matter their source or how high the specificity of their selectors.
    • Exception: will not allow inheritance to override specificity.
    • Diagnostic tool; should always be removed from the CSS after conflicts have been resoved.
    • Can be used in a user style sheet to override author styles.
  • In-line styles: 1,0,0,0 (these can only occur within the XHTML document, so they override the author's CSS)
  • ID selectors: 0,1,0,0 (the CSS cannot have in-line styles, so it always starts with 0)
  • Class selectors: 0,0,1,0
  • Element selectors: 0,0,0,1
  • Declaration Order: when two styles are the same, the last one will take precedence.

Inheritance

  • Has no specificity, so always loses to directly assigned value.
  • Terminology:
    • Ancestor: an element that is on a path between a given element and the root element in a document tree.
    • Descendent: an element on a path the descends from a given element.
    • Parent: a direct ancestor (the element directly above a given element).
    • Child: a direct descendent (the element directly below a given element).
  • Precedence (highest to lowest):
    • Properties defined for child and descendant elements
    • Properties defined for parent and ancestor elements

  • Properties that are not inherited:
    • borders
    • margins
    • padding
    • float

Positioning

Box Model

  • All block-level elements have a virtual box drawn around them.
    • Block box: properties:
      • Can be made to appear inline with "display: inline".
      • Block box properties:
        • div
        • h1 - h6
        • li
        • p
    • Inline boxes:
      • Can have an indefinite number on the same line of text.
      • They can wrap from line to line.
      • Can be made to appear block with "display: block"
      • Inline box properties:
        • a
        • b (generates an inline box)
        • img
        • span
      You can have
  • Content is surrounded by:
    • margin --> border --> padding --> content <-- padding <-- border <-- margin

Margins

  • Always transparent by default.
  • You can change this by declaring background properties.

Float

(for Positioning Elements)
  • Placing an element on the Web page and letting other content flow around it.
  • The floated element should be embedded in the content that is to flow around it; e.g., embedded in the text of a paragraph.
  • Can be applied to any element; e.g., floated elements can be everything from a complex image to a paragraph (like a printed insert or sidebar).
  • You can float left, right, or none (not center).
  • Float is not inherited.
  • You will need to set a margin for the floated element to keep the flowing content from "bumping up against it".
  • Set margins to em if you want them to scale with the font size, or to px if you don't.

Float

(for page layout such as creating columns)

Form:

  • #content {
    • float: left;
    • width: 50em;
  • }
  • #sidebar {
    • float: right;
    • with: 20em;
  • }

Eliminating Column Drop

(essentially, floating one element over the padding of another):
  • First floated element:

    1. Remove the width from the "Content" division:
      • #content {
        • float: left;
      • }
    2. With no width restriction, the float will expand to fill the screen, bumping adjacent floats to down below.
    3. Add sufficient padding-right to leave room for the next floated element.

  • Second floated element:

    1. Leave the width property in place.
    2. Add a left margin to the next floated element that is:
      • Negative.
      • Numerically greater than the element's assigned width (e.g., -18em if the element is actually 17em wide).
      This tricks the browser into thinking the float has no width, and will therefore fit next to the previous float.

Using Containers for Floats

If a container holds only floated elements and no normal flow elements, it collapses to have no height at all. To resolve this:

  • Float the container div (e.g., float: left;).
    • Since there is no content, the right margin of the container div will expand to fill the screen, and your other floated elements will float on top of it.
    • Problem: the size of the container is not constrained by the width of the content area. Consider:
      • #container {
            float: left;
            border: 2px solid red;
            width: 100%;
        }

      width: 100% refers to the content (in this case, the floated elements) of the container div only.  
      The border on the container causes the width to extend beyond the edge of the screen, making a horizontal scroll bar appear.

  • Remove both the width and float declarations, but add overflow:

    • #container {
      • border: 2px solid red;
      • overflow: auto;
    • }
  • -   This allows the container width to adjust to hold the floated elements and the border.
  • -   Had the declaration been "overflow: hidden", the container would still extend beyond the edge of the screen, but rather than having a scroll bar appear, the overflow would just become invisible.

Troubleshooting and Cautions

  • If the first float slips under the second float, increase the first float's padding-right.
  • Negative values can only be applied to margins, not to padding.   Padding can never be less than zero.
  • width: 100% causes horizontal scroll bar to appear: width applies to the contents only. Padding, borders, and margins can cause the element to extend beyond the screen width.  Solution: set overflow: auto.

Clear

  • Values:
    • left: position this element below any left floating elements.
    • right: position this element below any right floating elements.
    • both: position this element below any floating elements.
    • none: overrides any floats set up an external CSS.

  • Top margin on cleared element is overridden and set so only the visible portion of the cleared element will show below the floats. To create vertical space between the cleared element and the floated elements above it, add a bottom margin to all the floated elements -- all, because their sizes might change, and the margin might not work if it is on the shorter floated element.

Positioning Elements

  • Forms:
    • .header {position: absolute; top: 0px; left: 0px; z-index: 1;}
    • .shiftLeft {position: relative; left: -1ex;}
    • .shiftRight {position: relative; right: -1ex;}
  • Absolute: positioned relative to the containing block-level element
    (e.g., body).
  • Relative:
    • Positioned relative to other elements.
    • Warning: can cause overlapping text
  • z-index property: for overlapping elements. Higher valued elements are displayed
    in front of lower valued elements.
  • ex is:
    • the x-height of a font
    • a relative-length measurement
    • equal to the height of a lowercase x

General Information

Compiling

For XHTML and CSS, the browser is the compiler. It will strip out comments, which are designated as follows:

  • XHTML: <!-- -->
  • CSS: /* */

Fonts

  • Sans-serif (e.g. Ariel) is easier to read on a screen.
  • Serif (e.g. Times New Roman) is easier to read on paper.
  • Use relative measurements (e.g., em or ex) rather than absolute measurements such as pt.

Inline and Block-level Elements

  • Any of the following can themselves be styled; e.g.:
    span {color: red; font-size: .6em; height: 1em}
    .super {position: relative; top: -1ex;}
    <span class="super">
  • Inline-level elements:
    • a
    • b (generates an inline box)
    • em (one font-size; e.g., with "font-size: 10px;", 1em = 10 px)
    • img
    • span
    • strong
  • Block-level elements:
    • div
    • h1 through h6
    • li
    • p
  • Block level elements render with a line break before and after their content.  To bypass this:
    • display: inline, or
    • div.classname {float: right}
  • Block-level backgrounds: how we affixed the NoteLinks header to the top of the page:
    • #masthead {
          width: 65% (allows page to resize)
          background-image: url ('../images/notelinksHeader6Background.jpg');
             (a section taken from the left edge of the header jpg)
          background-repeat: repeat-x;
             (causes illusion of seamless expansion when repeated along the x-axis)
          position: fixed;
      }
    • background-position:
      • Keywords: top, bottom, center, left, right
      • Can be used individually or in combination
      • Alternative: horizontal length followed by vertical length
        (e.g. background-position: 50% 30px; positions half way
        across the screen and 30px from the top of the screen).

List Images

  • Form: ul {list-style-image: url(image.jpg);}

Managing Style Sheets

Single sheet for many pages (inked or imported)

  • Pros:
    • Change entire site by editing one sheet.
    • Sheet is cached, reducing load time and bandwidth.
  • Cons:
    • For large sites with many layouts, a single sheet:
      • Can become so large that it will strain bandwidth.
      • May contain unnecessary content for users viewing only a page or two.
      • May put undue strain on the server, as each user has to load the entire sheet.

Sectional styles

  (one basic style sheet for the whole site; additional ones to define each section)
  • Examples:
    • "Shell" style sheet is used by all pages to set up a basic look.
    • "Section" style sheets make products shades of green, support shades of blue, etc.
  • Pro: website can be controlled from a central point while easily differentiating sections.
  • Con: if the XHTML markup changes, multiple CSS files may be affected.

Modularized Styles

  (one sheet per section of design rather than per section of site)
  • Examples:
    • A global style sheet for headings, paragraphs, link colors, etc.
    • A modular style sheet for the masthead.
    • A modular style sheet for the the main content.
    • A modular style sheet for the footers.
  • Pro: updating just an area of the page is easier.
  • Cons:
    • Can prove unwieldy if several modules.
    • Could result in numerous link elements on each page (though this is still more efficient than embedding).
  • Workaround:
    • Import the modules that will affect every page (masthead, main, footer) through a single linked style sheet.
    • This reduces the number of link elements in each XHTML page.
    • If modules are added, additional @imports can be added to the one linked sheet.
    • Note: since "link" is an XHTML element, it cannot be used in an external CSS.  "@import" must be used in the CSS instead.

Chained

  • Variation of modularized styles.
  • Uses imports to chain external style sheets together, with a link only to the last style sheet in the chain:

    HOME PAGE -------------→ Home CSS ----------------------------------→ Shell CSS
                                                                                                         ↑
    RESOURCES PAGE --→ Resources CSS --→ Variable Width CSS ---|
                                                                                      ↑
    DEFINITIONS PAGE --→ Definitions CSS ---------------------|

  • Pro: just one link element per XHTML page.
  • Con: more complex; requires close knowledge of which CSS forms exist, and how they are chained.

Margin

  • Expansion:
    • If the overall box does not fill the entire width of the parent area, the right margin expands to fill the gap.
    • This happens for elements with normal flow (text; not floated, positioned, or laid out in any particular way)
    • To expand the left margin instead (which moves the text to the right), set the left margin to auto; e.g., margin: {10px 10px 10px auto;}
    • To center the text: margin: {10px auto 10px auto;} OR margin {10px auto;}
  • Width attributes are set clockwise from top: {top  right  bottom  left}

Media

  • Common Types:
    • aural
    • braille
    • handheld
    • print
    • screen
  • A specific type (e.g. print) has a higher specificity than the type all.
  • For a complete list and details, see http://www.w3.org/TR/CSS2/media.html
  • Media type can be set in the head section through a CSS link (as in this document),
    or through a style declaration as follows:
    • <style type="text/css">
          @media print
          {
              body {background-color: white;}
              h1 {color: #008844;}
              p {font-size: 14pt;
                  color: #4488aa;
                  font-family: "times new roman", times, serif;}
          } /* end @media print declaration */
      </style>
  • Not supported by IE6 and earlier versions.

Pseudoclasses

  • Example: a:hover {color: blue;}
  • Content not specifically declared in the document
  • Separated by a colon and no spaces from the element to
    which it is applied.

Property List

  • background
  • border
    • -width
  • color
    • Hexadecimal
      • long; e.g., color: #cdeaeb;
      • short; e.g.; color: #999; (for repeated values like #999999)
    • Red, Green, Blue (RGB)
      • percentage; e.g., {background: rgb(nn%,nn%,nn%);}
        • black = rgb(0%,0%,0%)
        • white = rgb(100%, 100%, 100%)
      • integer: defines red, green, and blue on a scale of 0 to 255
        • black: rgb(0,0,0)
        • white: rgb(255,255,255)
    • Named colors; e.g., color: red;
  • display
    • -block
    • -inline
    • -none (literally means "do not display a box for this element")
  • float
  • font
    • -size
    • -style: oblique (more slanted than italic; defaults to italic if oblique is not supported)
  • letter-spacing: 5px; causes 5 pixels of spacing between letters: Letter Spacing = 5px
  • list
    • ul
    • ol
    • dl (definition list)
  • list-style
    • -none (suppresses the list marker)
  • margin
  • overflow
    • -scroll (if the content inside an element exceeds the set boundaries, scroll bars are added).
    • -hidden clips any content that is longer or wider than the container element.
    • -auto allows the container element to resize to include content that is longer or wider than the container element.
  • padding
  • text-indent: indents first line of text in an element by a specified amount.
  • text-transform (used to change case: e.g., "text-transform: lowercase;" renders "Test Transform" as " text transform")
  • visibility
    • -hidden (essentially the same as "display: none")
  • width:
    • Sets the width of the element only.   Does not include margin, padding, or borders (see "Box Model" above).  The width of these must be set separately..
    • 10em = 10 times the font size.

CSS3

Background images

  • Set the size
  • Specify an offset
  • Use multiple background images in one element

Borders

  • Multiple colors
  • Images for borders
  • Rounded corners

Boxes

  • Add shadows
  • Resizable

Layouts

  • multicolumn
  • Selectors: enhanced
  • Styles: more developed speech (aural)
  • Text:
    • Set shadow effects
    • More overflow options