CSS Syntax | Monolith Design

CSS Syntax

Overview of Cascading Style Sheets

Cascading Style Sheets (CSS) is the W3C standard for the visual presentation of Web pages. The basic idea is that CSS provides a mechanism to specify the appearance, position, and behavior of all elements on an HTML page. Furthermore, these definitions can be selectively applied to elements in a group of pages, allowing you to change the appearance of all those elements in a single place—the style sheet. This also reduces the size of your HTML pages, since you’re able to drop a lot of redundant markup.

In the olden days, page layouts were created by forcing elements into cells of tables, usually nested in intricate ways. Table-based layouts add a large amount of markup HTML to your pages, and can easily obscure the underlying structure of the page. Worst of all, table-based layouts are notoriously brittle—moving an element from one side to the other can involve moving tables-inside-tables-inside-tables or worse, the equivalent of major surgery. We won’t be using tables for layout in this class, but you will still see them in use as you look at Web pages!

If you want to explore what is possible with style sheets, check out the CSS Zen Garden, where there are dozens of pages with the exact same content but different style sheets. You will be amazed at the variety!

Three Ways to Define Styles

  • External Style Sheet: style definitions can be listed in an external file, allowing those styles to be changed in one place for all files that use that style file. All production sites use external style sheets. You can use the <link> tag to load the CSS file, and it is exactly as if the contents of the CSS file were inserted into a <style> section in the HTML.


    <link href="CSS/CIS86.css" rel="stylesheet" type="text/css" />

  • Embedded Style Sheet: a style sheet can be embedded in the HEAD of a single HTML file using the style attribute. You can start development with an embedded style sheet, and then extract the style info into a separate file when the design stabilizes.

    <style type="text/css">
    /* This is a comment in a style sheet or <style> tag in the <head>. It can be multi-line, too. */
    h1 { font-size:250%; color:#0066cc; background-color:#eeeeee; }
    #topbox { border:3px solid #ffffcc; color:#0066cc; }
    #toplist { list-style-type:none; }
    .warning { background-color:#ffddee; font-weight:bold; }
    .explain { padding: 0 20px; }
    </style>

  • Inline Styles: applied to an individual element via the style attribute. These are usually the most specific styling, but it is hard to modify this when it’s embedded directly into the code where it’s being applied. You should really avoid this as a matter of habit, but there are times when it makes sense.

    <h2 style="margin-left:20px; font-size:150%;">An example header.</h2>

4 Ways to Attach Style Info to Elements

Once you have created your style info, whether linked in from another file or embedded in the <head> of your file, there are four ways you can associate the CSS with actual page elements. You can use any or all of these methods on each page element.

  1. Apply styling directly to HTML tags. You can define (and redefine) the behavior and appearance of HTML tags within your pages.
  2. Declare a class for an HTML element, which then receives all of the styling specified in that class. You can even apply more than one class to a given element. Each class can be applied to any element on the page, even to different kinds of elements.
  3. Declare an ID for a single HTML element on the page. Each ID uniquely identifies that element on the page, and the element receives all styling defined for that ID. You can have as many IDs as you want, but each one can only be applied to a single element per page. This is commonly used to identify the major "chunks" of the layout like the header and footer. If you put an ID on the body tag, you can highlight the current page in navigation.
  4. Declare inline styling directly for page elements using the style property. This technique should be used sparingly because it reduces flexibility while introducing opportunities for errors.

Here are examples of applying styles in the body, using the style definitions just above:

<div id="topbox">Blah, blah, blah….</div>
<ul class="warning" id="toplist">…list contents…</ul>
<p class="explain">This is an explanation.</p>
<div class="explain warning">blah….</div>

<span style="font-weight:bold; color:#996633;">This is bold and red.</span>

Four things you will find in CSS files or embedded stylesheets

  1. Comments, as delimited by /* and */. These can be multi-line.
  2. HTML tags, followed by a declaration block.
  3. Class names (a dot followed by a label), followed by a declaration block.
  4. IDs (a ‘#’ followed by a label), followed by a declaration block.

Structure of Style Rules

  • Every style rule has two parts: the selector(s) and the declaration block. A CSS rule contains at least one selector and at least one declaration within a declaration block.
  • The selector specifies which parts of the document should have the style rule applied, by assigning style information to
    specific elements or groups of elements. You can have multiple selectors listed, and the styling in the declaration block applies to everything that matches all selectors. You can also specify combinations of selectors with specific relationships. For example, "h1+p" targets the first paragraph following an h1 tag. There are 3 kinds of selectors:

    • Generic selectors are HTML tags, allowing you to change the appearance of all instances of specific tags.
    • Class applies style to all elements of that class.
    • ID applies style to the single element defined with that ID (name).
  • The declaration block contains one or more declarations, and is always enclosed in curly braces. A declaration consists of a property name, a colon, and a corresponding value. Declarations are separated by semicolons.
  • Examples:     
    • body { color: #ffffff; background-color: #000000; }
    • img { border: 3px solid #cccccc; }
    • #menubar {position: absolute; top: 100px; left: 0px; width: 180px; }
    • h1, h2, h3 { color:#cccccc; text-transform:capitalize;}
    • .question, .explain {font-color: #ff0000; font-weight: bold; }
    • .rightcolumn h2 { padding-left:56px; background: url(../images/small-sun-icon-sidebar.jpg) left no-repeat; }
    • p.explain ol li { list-style-type: disc; }
    • h1+p { font-variant:small-caps; }

Pseudo-Class Selectors

A pseudo-class selector is a predefined class-like selector. They are written with a colon, followed by the predefined pseudo-class name. Some of these allow dynamic behaviors, such as with link anchors. The W3C specification says that you can attach pseudo-classes to any element, but Internet Explorer only really supports them for link anchors. Here is how to use them:

  • :link selects links that have not been visited.   a:link { border-bottom: 2px solid #ff0000; }
  • :visited selects links that have been visited.      a:visited { border-bottom: 2px solid #0000ff; }
  • :hover selects an element when the mouse hovers over it.      a:hover { background-color:#cccc99; }
  • :active selects a link that is being activated.   a:active { color:#ffc600; }
  • :focus selects the element that has the focus.   a:focus { outline:0; }

If you use these selectors for links, specify them in this order ("LVHA" = "Love-Hate")! You can get unpredictable results in some browsers in some conditions if you do not follow the order.

Resolving Conflicts in Style Declarations (the Cascade)

The Cascade part of CSS is the mechanism by which conflicting style directives are sorted out. This can be a most complex subject, but the gist of it is that usually the definition that takes precedence is the closest definition to the place in the source file where it is being used.

Another thing to realize is that there is a default value for every possible HTML and CSS construct you may use. These default values vary slightly from one browser to the next, so you have to either compensate for the foibles of individual browsers, or reset all of those defaults to zero or equivalent (this is called a "CSS reset"—see the Canonical CSS file for an example).

Since style directives can be applied in many ways in a single file, CSS uses the cascade to resolve any conflicts between style definitions.

  • The source of the style sheet determines its importance, in this order: the Web browser’s default style sheet is overridden by the Web designer’s style sheet, which is overridden by the user’s style sheet (in the unlikely event the user specifies a private style sheet). As a designer, you can add the "!important" declaration to a rule to give greater weight to a rule.
  • Specific selectors are given greater weight than general selectors. Here are the types of selectors in order of weight (least to most): Universal (applies to all elements) > element identifiers (applies to all elements of a certain type, such as table) > class identifiers (all elements of class "foo") > ID identifiers (the element named "menubar") >
    inline styles (make this thing red right here). For example, setting the background color for a paragraph named "overview" will have greater weight than a general assignment of background color to the page.
  • If selectors have identical characteristics, then the selector that appears last in the style sheet file will take precedence. Selectors defined in an external file are considered to come before any style defined within the page (whether embedded or inline).

Most Common CSS Properties

Here is a description of the most commonly-used CSS properties. In certain cases, you will also find so-called shorthand properties that let you combine related properties into a single property declaration. For example, you can say:
font: 1em/1.5em bold italic serif
instead of
font-size: 1em; line-height: 1.5em; font-weight: bold; font-style: italic; font-family: serif

When specifying padding, margins, and borders, you usually have to specify what you want to happen for different sides. A single value for any of those properties results in an identical value being applied to all four sides. If you want to specify all 4 sides differently, remember the acronym TRBL, which means Top-Right-Bottom-Left.

   padding:4px;    (applies 4px padding to all 4 sides of the element)
   padding:4px 6px 12px 6px;    (applies to top, right, bottom, and left sides)
   padding:4px 12px;    (applies 4px to top and bottom, and 12px to right and left sides)

Font Properties

  • font (shorthand property)
  • font-family
  • font-style
  • font-variant
  • font-weight
  • font-size

Text Properties

  • word-spacing
  • letter-spacing
  • text-decoration
  • text-transform
  • text-align
  • text-indent
  • line-height

Colors & Background Properties

  • color
  • background-color
  • background (shorthand property)
  • background-image
  • background-repeat
  • background-attachment
  • background-position

Box Properties

  • height, min-height, max-height
  • width, min-width, max-width
  • float
  • clear
  • margin (shorthand)
  • margin-top, margin-right, margin-bottom, margin-left
  • padding (shorthand)
  • padding-top, padding-right, padding-bottom, padding-left
  • border (shorthand)
  • border-top, border-right, border-bottom, border-left (shorthand)
  • border-width (shorthand)
  • border-top-width, border-right-width, border-bottom-width, border-left-width
  • border-color
  • border-style

Lists

  • list-style (shorthand)
  • list-style-type
  • list-style-image
  • list-style-position

Display, Position, & Visibility Properties

  • position: discussed in section about Layout
  • display: block, inline, none
  • visibility
  • overflow
  • white-space

Miscellaneous Properties

  • Certain properties need a URL for the background image:
    background: url(images/stripe.gif) or background: url(http://www.htmlhelp.com/stripe.gif)

There are many CSS References online, including the table from Elizabeth Castro in the back of her book (and her Web site) and this one from htmlhelp.com.

Additional Topics

Here are some related topics about using CSS.

  • How I center something? Where did that <center> tag go?
    • For text, use the text-align property:    <h2 style="text-align:center;">Headline will be centered!</h2>
    • For block-level elements, use margins:   <div style="margin:0 auto;">The box will be centered.</div>
    • Unfortunately, some versions of IE mishandle this. This example of centering a fixed-width box in the browser window also employs the fix for IE (misuing text-align). You can see this in play in the class Web site’s style sheet.
      body { text-align:center; }    this will center everything in IE, not just text
      #maincontent { width:80%; margin:0 auto; text-align:left;}    auto margins = centered
  • How can I make columns? Here are various approaches to making columns, depending on your exact needs.
    • If you are presenting tabular data, use a <table>.
    • Use a margin to free up a column alongside something, and then fill the empty column with an absolutely-positioned element.
    • Create a container to wrap around the group of columns, then use float:left on the individual columns inside that container. The columns will stack up towards the left side of the containing box.
    • Create a container to wrap the group of columns, and use position:relative to establish a positioning context. Use position:absolute to place the columns where you want within the containing box.
    • The specification for CSS3 allows you to create columns, but we are years away from any kind of widespread acceptance by browser vendors.
  • Overflow: what happens when the contents are larger than the box? You can override the default behavior using the overflow property:
    • overflow:visible (the default) will expand the container to fit the contents as needed
    • overflow:auto lets the browser add scrollbars only when needed
    • overflow:hidden will truncate anything outside the container’s bounds
    • overflow:scroll will always show scroll bars

Multiple Style Sheets per Page

You can specify more than one style sheet per page, and there are some good reasons for doing so. In the following example from the class Web site, I have added a media property that allows me to target printed versions of the pages.
<link href="CSS/CIS86-Print.css" rel="stylesheet" type="text/css" media="print" />

In this version, I have removed some navigational code and tweaked widths for better printing. CSS also provides attributes for specifying where page breaks can happen. This is also an opportunity to tweak your colors for better contrast when printing.

Other media types allow you to target mobile devices, an up-and-coming need for certain Web sites.

Another possible use of multiple stylesheets is to provide alternate choices to a person browsing your site. Most commonly, the user is allowed to select a smaller or larger base font size for the page. You can also make other adjustments for different sizes.

When using multiple stylesheets, pay attention to which sheets are actually being loaded. Use media="all" to target everything. When you use more restricted media, make sure you control which other style sheets are being loaded.


QR Code Business Card