Cascading Style Sheets (CSS) provide a higher level of abstraction over the presentation of web pages. The definitive guide to CSS2 is at the www.w3.org.

  1. Reasons to use CSS
    1. CSS separates your content from presentation (think MVC).
    2. With CSS an entire web site can change look by changing one file (csszengarden).
    3. Using CSS can lower your bandwidth costs.
    4. Your HTML is easier to read and understand making maintenance cheaper.
    5. People with disabilities can access your pages easier.
    6. Organizations can share the same style across web sites.
    7. Menus can be created without javascript.

    Old Style:

    <p><font size="7" face="Georgia, Arial" color="red">Error: 
    I'm sorry Dave, I'm afraid I can't do that.</font></p>
    

    New Style with CSS

    <p class="error" >Error: 
    I'm sorry Dave, I'm afraid I can't do that.</p>
    
  2. Rules
    1. General format of CSS:

      A CSS is composed of a series of rules. A rule is a "type selector" followed by curly braces enclosing one or more "declarations". A declaration is composed of a property, a colon, a value, and a semi-colon (the last one before the '}' is optional). White space is not significant between tokens.

       
      selector {
        propertyName1: propertyValue1; 
        propertyName2: propertyValue2; ...
      }
      
    2. Selectors
      1. Element Type Selector

        Example of specifying attributes for a single element type

        h2 { 
            font-size: 16pt; 
            font-family: arial,helvetica,"sans serif";
            color: black; 
            font-weight: normal;
           }
        

        Note: property values with more than one word should be placed in quotes as above with "sans serif".

      2. Universal Selector

        This effects all elements

        * {
        color: green;
        }
        
      3. Class Selector

        The "." is the class selector character. This affects all elements with a particular "class". ("Bundle" would have been a better name. A class is a predefined bundle of css rules.)Define a class by giving it a name (always preceded by a period) and adding the standard style definition of properties and values inside curly brackets:

             .periwinkle { color: #6699ff; } 
        
        in the document:
         <p class="periwinkle">This is bold, periwinkle text.</p> 
        
        becomes:

        This is bold, periwinkle text.

        You can specify that a style will apply only to a particular element type. For example, only paragraphs with the class "periwinkle" will be affected by the following:

        p.periwinkle { color: #6699ff; } 
        

        Elements may have more than one class, separated by spaces

        If the style sheet contains:
        .periwinkle { color: #6699ff; } 
        .tiny  { font-size: 70%; } 
        
        And the text is:
         <p class="periwinkle tiny">This is tiny, periwinkle text.</p> 
        
        The result will be:

        This is tiny, periwinkle text.

      4. id Selector

        This effects the single element with this "ID". In the style sheet, ID selectors are prefaced with a '#'.

             #big { font-size: 250%; } 
        
        in the document:
         <p id="big">This is BIG text.</p> 
        
        becomes:

        This is BIG text.

      5. Pseudo Element Selectors

        This are used to style particular parts of an element. Pseudo Elements are prefaced with "::" to distinguish them from Pseudo Class which start with a single ":". Common examples are: ::first-line, ::first-letter, ::selection, ::before and ::after. (The "::" is not supported in all browsers, although some take a single colon nicely. IE is still having issues with some of these.)

        p.test:first-letter { 
          font-size: 200%; 
          float: left; 
          font-style: italic;}
        ...
        <p class="test" style="border: solid thin;">
        Once upon a time there were four little rabbits, 
        and their names were
        Flopsy, Mopsy, Cotton-tail and Peter.</p>
        
        This will render correctly on Firefox and a little awkward in IE6:

        Once upon a time there were four little rabbits, and their names were Flopsy, Mopsy, Cotton-tail and Peter.

      6. Dynamic Pseudo Class Selectors

        For elements that change over time or conditions. CSS2 defines hover, active, focus, link, and visited,lang(). Example: if the style sheet contains

        a.test:hover {
        background-color: red;
        }
        

        and the html looks like this:

        <a href="#" class="test">Example link with red background.</a>.
        

        This will render with a red background when the cursor hovers over it:


        Example link with red background..

        To specify a color for visited links,

        a:visited {
           color: #999;
        }
        
      7. Structural Pseudo Class Selectors

        These select elements based on their position in the structure of the document. Examples: :root, :first-child, :last-child, :empty. This is defined in CSS3 and is supported by most browsers, but not IE.

      8. Parent Child Selectors

        To specify that when an element is a direct descendant to another to use a particular style

         
        li>p { font-style: italic; }
        

        then paragraphs appearing inside of list items will be in italics only if they are direct descendent's

      9. Descendant Selector

        You can assign properties to elements that descend from another element. For example, all "em" tags descended from a "p" tag will be 120% than normal.

        p em { font-size: 120%; }
        

        "I believe I have peace in our time."

      10. Adjacent Selectors

        Specify a rule when two elements are next to each other. This applies to the element on the right.

         
        li+p { font-style: italic; }
        

        The paragraph adjacent to the "li" element will be in italics.

      11. Attribute Selectors

        Applies rules to elements with particular attributes and values

         
        input[type="text"] { font-style: bold; }
        
      12. font-variant can be used to give special effects like small caps

        <H2 style="font-variant: small-caps">

        Example:

        Napoleon defeated at Waterloo!

      13. More than one selector can be on the same line separated by commas

        In this example all h1, h2, and h3 elements are declared to be red.

        h1, h2, h3 { 
         color: red; 
        }
        
      14. To specify that when an element is contained by another to use a particular style, do not use commas,

        Example: li p { font-style: italic; }

        then paragraphs appearing inside of list items will be in italics

  3. Style Sheets

    Style Sheets are files typically with a ".css" extension containing rules. The four and a half ways of linking pages to Style Sheets:

    1. External

      Use an external file and specify it's location with the "link" command in the head section (preferred method). More than one can be included.

      <?xml version="1.0" encoding="UTF-8"?>
      <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
               "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
      <html xmlns="https://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
      <head>
      <title>KnowledgeBase/Web/CSS - Examples of CSS</title>
      <link href="https://www.fincher.org/mystyle.css" rel="stylesheet" 
              type="text/css" />
      <link href="https://fincher.org/style/css.css" rel="stylesheet" 
              type="text/css" />
      <meta name="description" content="Examples of CSS" />
      <meta name="keywords" content="CSS" />
      <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
      </head>
      
      <body>
      ...
      

      The file "mystyle.css" would contain something like,

      h1 {border-width: 1; border: solid; text-align: center}
      h3.green { font-family: Arial; font-style: italic; color: green }
      span.html { color:#ff0000 }
      
    2. Embedded
      <head>
        <style type="text/css">
        h3 { font-family: Arial; font-style: italic; color: green }
        h1 {border-width: 1; border: solid; text-align: center}
        h3.green { font-family: Arial; font-style: italic; color: green }
        span.html { color:#ff0000 }
        </style>
      </head>
      
    3. In line

      CSS commands can be used in a tag declaration:

      <h2 style="color:blue">My Subtitle<h2>
      
    4. Import with '@'

      In the heading section put something like,

      <style type="text/css">
         @import url(https://fincher.org/mystyle.css);
      </style>
      
    5. Nesting Style Sheets

      A style sheet can import another style sheet. For example in my "Beach.css" style sheet I have the following:

      @import url("https://www.fincher.org/style/Menus.css");
      @import url("https://www.fincher.org/style/Basic.css");
      @import url("https://www.fincher.org/style/Position.css");
      body {
        background: url("https://www.fincher.org/images/Sand-1280.jpg");
        background-attachment: fixed;
        background-repeat: repeat;
        background-position: center;
      }
      

      Inside "Plain.css" we reuse the simple style sheets and add specific colors:

      /* body */
      @import url("https://www.fincher.org/style/Menus.css");
      @import url("https://www.fincher.org/style/Basic.css");
      @import url("https://www.fincher.org/style/Position.css");
      body {
        background-color: transparent; 
        color: black;
        text-align: center;
        background-attachment: fixed;
        background-repeat: repeat;
        background-position: center;
      }
      

      Note: comments in css are put inside "/*" and "*/" strings.

  4. Length Units

    CSS provides many units. Relative units are usually preferred since they are more flexible.

    1. Relative Units
      1. em (ems, the height of the element's font)
      2. ex (x-height, the height of the letter "x")
      3. px (pixels, relative to the canvas resolution)
    2. Absolute Units
      1. in (inches; 1in=2.54cm)
      2. cm (centimeters; 1cm=10mm)
      3. mm (millimeters)
      4. pt (points; 1pt=1/72in)
      5. pc (picas; 1pc=12pt)
    3. Percentage

      A percentage value is prefaced with an optional + or -, followed by numbers, followed by %. Example: .tiny { font-size: 70%; }

  5. Examples of using selectors
    1. Changing the look of an element.

      To change all instances of an element:

      <head>
              <style type="text/css">
              <!--
              h3 { font-family: Arial; font-style: italic; color: green }
              -->
              </style>
      </head>
      
      Then the following HTML code
      <h3> This is a green Arial header3 </h3>
      
      becomes

      This is a green Arial header3

    2. span is good to use for text inside a paragraph. example

      Inside the header section put something like,

      <style type="text/css">
      span.javascript { color:#00aa00 }
      span.lang { font-size: 18pt; color:#0000aa; }
      </style>
      

      And then in your text enter,

      My favorite language is <span class="lang">Ruby</span>!
      
      Then your text will look like this:
      My favorite language is Ruby!
    3. To use style sheets inside a table, you can use TH and TD
      <style type="text/css">
      <!--
        body, th, td  {font-family: Comic Sans MS,Helvetica, 
                           Verdana, sans-serif;font-size: 10pt;}
      -->
      </style>
      
    4. Text Decoration

      the "text-decoration" property modifies the text.

      Possible values: none underline overline line-through blink

      .title { text-decoration: underline; }
      
      <div class='title'>State of Fear</div>
      
      becomes:
      State of Fear
    5. Text Transformations

      the "text-transform" property can format text. Common values are capitalize, uppercase, and lowercase. Example:

      <p style="text-transform: uppercase;">This is all uppercase.</p>
      

      This becomes:

      This is all uppercase.

    6. The "white-space" property

      The line breaks and white space can be preserved.

      <p style="white-space: pre; border: solid 1px black;">
      drip, drip,       drip,               drip
      the rain would not stop.
      </p>
      
      

      This becomes:

      drip, drip, drip, drip the rain would not stop.

    7. line-height

      To control the spacing between lines use line-height.

      <p style="width: 20em; line-height: 0.75em;" class="boxed">
      The sky above the port was the color of television, tuned to a dead channel. 
      (line-height: 0.75em)
      </p>
      

      The sky above the port was the color of television, tuned to a dead channel. (line-height: 0.75em)

      The sky above the port was the color of television, tuned to a dead channel. (line-height: 2em)

    8. The cursor can be set to a new shape by something like this:

      <span class="bordered" style="cursor: wait;">wait</span>
      

      Move your cursor over the following:

      crosshair pointer wait help move text
    9. Shorthand Properties

      Many properties are assigned over and over. To minimize wear and tear on our fingers the W3 allows many "shorthand" properties.

      instead of typing:
      padding-top: 3px;
      padding-right: 2px;
      padding-bottom: 1px;
      padding-left: 0px;
      
      You can enter,
      padding: 3px 2px 1px 0px;
      

      Note: Most shorthand properties follow the same Top,Right,Bottom,Left format, which is TeRrBiLe.

    10. Vendor-specific extensions

      Keywords and property names, beginning with '-' or '_' are for vendor-specific extensions. The vendor's code name immediately follows the '-' or '_'.

      -moz-border-radius: 3px;
      
    11. Precedence

      The wonderful thing about Cascading Style Sheets is that word "Cascading". You can set a general style for your web site and only override that style when you want an exception. Generally, the last most specific style wins. This can be overridden with the "!important" rule modifier.

      p { color: red !important; }
      

      Now, even though a more specific rule might apply to a paragraph, this "important" one will override it. In case of multiple "!important"s, the last one wins.

    12. To set a background image:
      background-image:url(https://fincher.org/images/gray_rock.gif);
      

      The rash of background properties (color,image,repeat,position, attachment) can zipped into the "background" shorthand property:

      background: url(https://fincher.org/images/BlueMarble.jpg); 
                  transparent no-repeat fixed top left; 
      
  6. Positioning
    1. Aligning blocks with "margin-right: auto" and "margin-left: auto"

      This paragraph is margin-right: auto.

      This paragraph is margin-left: auto.

    2. Using the overflow property

      "overflow" specifies how to display content that does not fit in the box.

      This paragraph uses "overflow: auto" with a fixed width and height and a thin solid black border.

      This paragraph uses "overflow: hidden" with a fixed width and height and a thin solid black border.

      This paragraph uses "overflow: visible" with a fixed width and height and a thin solid black border.

    3. "float" allows content to move to one side and be wrapped by other content. Floated elements are treated as block elements. Values for float are left, right, none, or inherit.

      I'm floated left.

      I am just regular old text, not floated at all.

    4. Block vs. Inline elements

      The following table details some differences between Block and Inline elements.

      Attributes Block Inline
      Accept attributes like width and heightYes No. Only as big as its contents
      WidthExpands horizontally to take up the whole line Expands only enough to contain its contents. Several inline elements can be on the same line comfortably, like bosons.
      May Contain Blocks and Inline elements Only other inline elements
      Examples <p>, <li>, <h1>, <form> and <div> <span> and <em>

      Elements can be changed from inline to block by using the "display" property.

      spanspanspanspan with display: block;spanspanspanspan

      As spans can be turned into block elements, block elements can be displayed as inline:

      <p style="display: inline" class="boxed">
      I'm an inline paragraph</p>
      <p style="display: inline" class="boxed">
      I'm an inline paragraph</p>
      

      I'm an inline paragraph

      I'm an inline paragraph

    5. To create layers

      Example shows how to use z-index to make one div float on top of another

      <div style="background: transparent; height: 40px; width: 250px; 
       position: relative; 
      font-size: 40px; z-index: 1;">Happy</div>
      <div style="background: transparent; height: 80px; width: 350px; 
      position: relative; top:-50px; left:30px; color:red; 
      font-size:80px; z-index:2">Birthday!</div>
      
      

      This produces:

      Happy
      Birthday!
    6. Using Css with tables

      table#joketable {
          background-color:#ccccff;
          width: 100%;
      }
      table#joketable td.author {
          padding: 5px;
          width: 25%;
      }
      table#joketable td.ratingbox { 
          padding: 0.4em 0 0 0.4em; 
          width: 25%;
      }
      

      For a table like this:

      JokeRate It! (25% width)Author (25% width)
      What did the bowling pin say to the bowling ball? "Please spare me!" 6 jeremy from New York
    7. To center tables in a page

      table { margin: auto; } 
      
    8. Special handling for printing

      CSS allows rules that apply only when printing. For example, the following prevents the menus and ads from this site from printing, since they are meaningless on paper.

      @media print {
              #menus, #adsRight, #adsBottom { display: none; }
      }
      
    9. How to center tables

      Since 'align="center" is frowned upon (and deprecated) use "margin: auto" to center tables.

         table {margin: auto; }
      
    10. Problems with CSS
      1. No variables, no inheritance
      2. Browser Support
      3. Browser Support (See acid2 test).
    11. Tools and Tip Sheets
      1. An essential tool for doing CSS is the "Web Developer" extension in Firefox. It's free. Try the "CSS / View Style Information" option - the cursor will describe the nesting level of the element beneath it. Try "Information / Display Element Information" to see more details about elements.

        Chrome has the best css/html inspector I think. On the mac enter Command-Option-i to bring up the window.

      2. A good cheat sheet by Robert Mening is here..
    12. The Really Big Idea behind style sheets

      I was reading a book on xml at Barnes and Nobles while my daughter was enjoying story time. I read a page that instantly changed my whole concept of HTML and browsers. The idea is this: All the HTML tags names are not magic, they just have a corresponding css style associated with them. You could write complete, valid, wonderful web pages using a whole new set of tags with an associated style sheet. Instead of using <p> you could use "my paragraph", <mp> and instead of <b> you could use <mb>, and <mem> instead of <em> if you set the style of these to something like:

      mp { display: block; text-indent: 2em; line-height: 90%;}
      mb { font-weight: 800; }
      mem { font-style: italic; }
      
      Then a sample text consisting of
      <mp>
      Twas brillig, and the <mem>slithy</mem> toves
        Did gyre and gimble in the wabe:
      All mimsy were the <mb>borogoves,</mb>
        And the mome raths outgrabe.
      </mp>
      
      <mp>
      "Beware the Jabberwock, my son!
        The jaws that bite, the claws that catch!
      Beware the Jubjub bird, and shun
        The frumious Bandersnatch!"
      </mp>
      

      would look like this:

      Twas brillig, and the slithy toves Did gyre and gimble in the wabe: All mimsy were the borogoves, And the mome raths outgrabe. "Beware the Jabberwock, my son! The jaws that bite, the claws that catch! Beware the Jubjub bird, and shun The frumious Bandersnatch!"

      So, the really big idea is that HTML tags are sort of a presupplied started kit of tags, but just an example of using CSS.

  7. Positioning

    CSS provides a way to position elements on a page and not merely to style them.

    1. static

      The default positioning for css is called "static". Elements are positioned in a normal flow from first to last.

      #outer, #one ,#two, #three, #four, #five   
         {position: static; border: thin gray solid; }
      #outer { background-color: #aaa; padding: 2em; }
      #one { background-color: #aaf; }
      #two { background-color: #afa; }
      #three { background-color: #aff; }
      #four { background-color: #faa; }
      #five { background-color: #ffa; }
      

      HTML code like the following:

      <div id="outer"> <!-- outer -->
      outer div
      <div id="one"> div one</div>
      <div id="two"> div two</div>
      <div id="three"> div three</div>
      <div id="four"> div four</div>
      <div id="five"> div five</div>
      </div> <!-- outer -->
      

      looks like this:

      outer div
      div one
      div two
      div three
      div four
      div five
    2. absolute

      "absolute" positions elements within their parent at particular locations.

      You can see what it looks like here.

      looks like this:

  8. Some of my favorite Online References for CSS:
    1. Introduction to cascading style sheets css/
    2. Layout techniques at https://www.glish.com/css/
    3. css1 properties
    4. Cascading Style Sheets
    5. w3.org's css validator
    6. w3.org's Cascading Style Sheets
Go to Home page. Kindly report errors, typos, or misspellings here.