Cascading Style Sheets

What are they, how do you build one.

An Introductory Primer by Libby Peters

Topics:

Definition:

CSS stands for Cascading Style Sheet. It is a language used specifically for development of the presentation layer of a website, a web page, a web application, or other pages rendered in web browser.

It allows for moving the presentation coding out of the html, jsp, or asp files and into a linked file to keep the files cleaner and easier to maintain. With this said, as all of you are aware when new ideas or technologies come into being the adoption of them is not universal among the myriad of browsers, operating systems, and devices on the market or in use. Almost all of the current browsers in use today support some level of “style” elements. The challenge in using this technology, as with any other, is to know what you are trying to accomplish, what your intended audience is, and the target operating systems/browsers.

If you are creating a web application that is for use by the public and you have determined that 25% of your public audience uses non-css browsers, you will want to limit your use of css to some of the older, more supported, inline style elements. If you are creating a website for a company intranet and you know that the standard install for browsers is IE v6 you know that you are safe to use linked style sheets that encompass more of the creative features of CSS2.

There are many sites that have charts with lists of what is implemented and what is broken in different browsers. One really comprehensive site with a listing of most of the style attributes is at “Web Standards and Software Learning” http://www.westciv.com/style_master/academy/browser_support/ .

For those of you using Macromedia Dreamweaver you can set up your Dreamweaver to check for browser support of your css and html files as you are building them and then run a report if you wish. This can be useful if you are doing team development.

Terms:

As with any language or new technology there are some terms that you need to become familiar with when using CSS.

Selector – The html tag or xml tag that you want to define the style of.

Declaration – The style attribute you want to apply to the selector.

DIV – A unique id assigned to a selector to identify a set of declarations. Should appear only once in a document.

Span – To enclose, or span an element or group of elements with a particular style.

Class - A specific type of selector that can be applied to an element or ‘spanned' around a partial element (such as a piece of text in a paragraph). In the style sheet it is always preceded by a period (.). Can appear numerous times in a document.

Elements - All of the lists, paragraphs, input boxes, text, etc. that make up an html, asp, or jsp page.

Block Element – An element that naturally displays as a block such as a paragraph, a list, a table, etc.

Inline Element – An element that naturally displays inline such as a piece of text, a link, a graphic, etc.

Why use CSS?:

As stated previously, css allows you to separate the presentation coding from the page coding to keep the pages cleaner and easier to maintain. In addition there are some other pretty compelling reasons.

One of the greatest of these is increased accessibility.

Before CSS tables had to be used as a way to position elements on a page, and sometimes endless, nested tables were used on a single page. This made for a page that was almost impossible for a screen reader to read. By using linked style sheets and properly marked up pages a screen reader has no problem reading a page. You can visually see what the screen reader is going to read by removing the link to your style sheet in the page and then opening it in a browser. What you will see is basically a text-only version of the page.

Another reason to use css is the capability to easily apply a style to like elements on a page without re-coding each item. For example if I want all of the input buttons on my page to look the same I will make a class called “buttonstyle” and apply it to every button. (example: <input type=”submit” class=”buttonstyle” value=”SUBMIT”>). This becomes increasing helpful if I am developing a whole website or web application with 100s of buttons. Each time I can just call the class instead of adding each of the style properties to the input button.

Inheritance or Cascading

CSS got it's name from the way the styles get displayed throughout the web page. The styles are said to cascade down through the page as would a waterfall. Just like a waterfall can have something divert the flow, the same is true in css. The diverters in this case are called style properties. It is very important if you are using multiple means to apply styles that you know in what order the browser applies the style rules.

The rule is that the style being applied closest to an element controls it's style. If you have a linked style sheet that makes all Heading Level 1 elements red, and an embedded style sheet that makes all Heading Level 1 elements purple, and an inline style that says that your Heading Level 1 is blue, your Level 1 Heading will be BLUE .

The other way that styles cascade down through a page is, of course, in the way your defined styles cascade down through the page as they are applied to the selectors. For example if you have defined the look (descriptors) for each paragraph (<p>) then each paragraph will be displayed in that style until another style rule diverts it.

HTML Object Properties

For those of you that have a pretty good handle on what all of the properties are that you can assign for page elements, you will have a jump on learning the css descriptors that can be used. For example all of the properties you can set for a font or for a block of text like <bold>, <em>, color, face, and size along with several others all have been folded into the descriptors for font, except for color. They are: font-family, font-size, font-weight, and font-variant. The one not in this group is font color, the descriptor for font-color is just color.

Syntax

So, how do you write a css file. First of all open your css editor (notepad). Here you are going to put your selectors, the descriptors, and any comments you feel would be beneficial to explain the intended use of the various styles.

First of all, use a good naming convention for your css file name and your selectors. If a style is to use for highlighted text make a class called .highlight. If a style is to use to make text red for error messages make a class called .errortext. Be careful about giving selectors and files names, names that refer to a section of the page that indicates direction or that indicates color because you may decide later that errortext is not red but orange or green or some other color. This is the same principle for naming based on current location, like left_menu. What if you move the left menu to the right, or to the top.

Secondly, start the css file with a comment line to describe the purpose of the following selectors and descriptors. CSS comments start with a ( /*) and end with a (*/). Here is an example:

/* A CSS file for the system menu pages */

Finally, start adding the selectors and descriptors. Each selector should be typed followed by a beginning curly brace, then the descriptor, a colon and then the descriptor value and a semi-colon.

When you are finished with the descriptors you close the statement with a closing curly brace.

Example:

p {

Font-family: Arial, sans-serif;

}

p {

font-size: 10pt;

}

p {

font-weight: bolder;

}

p {

color: red;

}

As you can see, this can get a little monotonous. There are some shortcuts to let you decrease the amount of work you need to do in creating a css file.

Grouping Selectors and Descriptors:

As you could see from what we did in the section above, this would be very time consuming to have to list every selector and every descriptor separately. Luckily there are many different short cuts you can use and some more advanced ones that we will not cover in this class.

To group selectors all you need to do is separate the list of selectors by a comma. For example if you want all of your headings (level one through 6) to be pink you can create an entry in the css file like this:

h1, h2, h3, h4, h5, h6{

color: pink;

}

 

This would work the same if it was just for ordered lists, heading level 3, and labels.

h3, ol, label{

color: red;

}

This can still get a little redundant if you have multiple attributes (descriptors) you want to use for each selector or a group of selectors. Say you want your paragraph text and any ordered lists to always have a font-size of 12pt, a font color of navy, and a font-weight of bold.

You can combine the selectors as we did above and also the descriptors like this:

p, ol{

font-size: 12pt;

font-family: Arial, sans-serif;

font-weight: bold;

color: navy;

}

Of course, if you have a need for an exception to the rule that you made you can override it by either interrupting it with a span.class or an actual inline style declaration.

Defining Containers – The Box Model

Above anything else that you can try to memorize about CSS, one of the most helpful is the relationship between a container (DIV) and its margins and padding and the actual contents.

The image below is a drawing of a box model.

This gets very confusing so here is how this walks thru in a text description. If you have a block of text you want to appear on a page and you want a margin all the way around the block of 10 pixels a 2 pixel border a 10 pixel padding all the way around the big block of text, you could describe it (starting from the left edge) like this: start your outer edge of the box come in 10 pixels, start the left border, come in 2 pixels, start the left padding, come in 10 pixels, start the left edge of the text, finish the text line, go out 10 pixels, finish the right padding, go out 2 pixels, finish the right border, go out 10 pixels, finish the right outer edge of the box. If you define a height and width of the container (DIV) the border, margin, and padding are added on to that area.

Using the description above with a text area of 200 pixels how wide is the entire div?

244 pixels. 20 for the left and right margins, 20 for the left and right padding

and 4 for the borders.

You can create some very interesting effects using negatives in the margins and padding, or placement of a background graphic. Some of these are fairly advanced. We will save the discussion of them to the intermediate/advanced css class.

Positioning: Relative vs Absolute

Relative positioning is fairly easy to understand. It is similar to how objects are positioned in html documents. Each element is placed in order relative to the element above it. In a box model if you have a box (div) inside of a box (div) each internal box element will be placed inside the internal box in relation to the other elements in that box. The margins, border, and padding that you set on the box element will be relative to the internal box outer edge not the larger box outer edge.

Absolute positioning is just what it implies. You declare that the element is to be absolutely positioned and then state what that position is going to be inside of it's container (div). The elements position in the linear flow of the html document does not take precedence. For example if you have the following html:

<html>

<head>

<title>Positioning Example</title>

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">

</head>

<body>

<div id="page">

<div id="helpBanner">

Put a graphic here.

</div>

<div id="navigator">

Put a page menu here

</div>

<div id="helpbody">

This is where the page content would go.

</div>

</div>

</body>

</html>

and you have the positioning on all of the selectors set to relative, without any other positioning declarations the page is going to flow straight down starting with the banner, then the menu, then the page body. Any margins and padding that you set will be in relation to how the box is placed inside the “page” box.

CSS File

#page {

position: relative;

top: 10px;

left: 10px;

}

#helpBanner{

position: relative;

top: 10px;

left: 10px;

}

#navigator{

position: relative;

top: 10px;

left: 10px;

}

#helpbody{

position: relative;

top: 10px;

left: 10px;

}

How far from the left edge of the screen is the box for helpbody going to be?

(20px).

If, in the above example we change the positioning of the navigator to absolute, it will stay within the main box (page) but it will be absolutely positioned 10 pixels from the top, which will be exactly over the top of the helpBanner.

There are good reasons to use either type of positioning, you just have to know where you want the boxes to appear on the page and what their relationship is to the container (box) that they are in. Absolute positioning allows for what web developers use to go crazy trying to get accomplished, the absolute positioning of a graphic. If you want a graphic to be 20 pixels from the top and 15 pixels from the left, always, absolute positioning will do that.

Note: It is very important to place the elements in their logical flow within the html, asp, or jsp page; even though you can reposition them, because if someone is dependant on a screen reader or they are looking at a text only version of the page, you want the page to flow linearly so that it will make sense.

Units of Measure

For those of you who do not know me, I really like math and trying to figure things out, so it is exciting for me to get to do some calculating in figuring out heights and widths and margins etc. for my web designs. There are many different measurements you can use, we will start with the simplest and move to the more complex. The simplest are static units of measurement: pixel (px), point (pt), percent (%), inch (in), cm, mm, Pica (pc).

For font size in addition to the ones above there are some relative measurements like smaller, larger, extra small (xx-small), small (x-small), medium-small (small), medium, medium large (large), large (x-large), very large (xx-large). These scale from either the base file size that you have set as the page default or from the base file size that a viewer has set as their preferences. The advantage of using relative font size indicators is that if someone has their preferences set to different than the norm (which many people do) you can distinguish items on a page with larger and smaller fonts and they will increase and decrease relative to their font size setting. If you use a static size (for example 14pt) for an emphasized heading it may not get the emphasis if 14 pt is the users default font size.

For widths and heights of a box or element you can use the static measurements above, or you can use some measurements that have been around since type-set was invented. These are the width of a typed “m” and the width of a typed “x”. There are declared as width: 15em (the width of 15 ms) or width:15ex (the width of 15 xs). These declarations are very helpful when working with input forms for labels and input boxes. Of course if you are using a true-type font such as courier the width of an m and an x is the same.

All of the measurements above, except for the relative font declarations, can be used for border widths, padding, margins, container width, container height, and positioning.

Fonts and Text:

There are a myriad of descriptors for effecting text most of which have been directly inherited from the html attributes for their counterparts.

Here is a partial list of the descriptors and their values:

Font-size

(see measurement section above)

Font-family

Font Name, font family name, font type

Color

Color name, hexadecimal value, operating system window colors, inherit.

Text-align

Left, center, right, justify

Text-indent

Length, percent

Line-height

Length, percent, number, normal

Letter-spacing

Length, normal

Word-spacing

Length, normal

Vertical-align

Baseline, sub, super, top, text-top, middle, bottom, text-bottom, percent, length

Font-style

Italic, oblique, normal

Font-weight

Normal, bold, bolder, thin, thick, 100-900

Font-varient

Small-caps, normal

Text-transform

Capitalize, uppercase, lowercase, none, inherit

Text-decoration

Underline, overline, line-through, blink, inherit

Because the combinations are endless with text and font declarations as far as what you can do, the key to learning these is to practice. Use the example page we have been working on and add at least one of each of the above declarations, save the file as fontexamples.htm and then open it in IE to view your changes.

Tip: Here is a shortcut you can use to set multiple font and text attributes with one CSS declaration.

P{ font: style variant weight size/line height font-family;} written like the declaration below.

p{font:italic small-caps 600 12pt/18pt Arial, Tahoma, sans-serif;}

Borders and Margins

Sometimes you want these and sometimes you don't, and sometimes you want them to behave in a way that would make sense when they display, but not following the general rule of all or nothing.

With html getting borders and margins to display properly was almost impossible. Now, thanks to CSS you can have much more pleasing, outlined and indented blocks (keeping in the mind the old print layout rule about good use of “white” space).

First a note about setting all of the margins, borders, or padding with one declaration. Here is a short cut that will save you lots of time as you are writing your CSS. You can declare all of your margins, borders, or padding with one declaration by putting the widths in clockwise order starting with the top. They don't have to all use the same unit of measurement. For example you could write: margin-top: 10px; margin-right: 20px; margin-bottom: 10%; margin-left: 10em; or you could write simply margin: 10px 20px 10% 10em;.

Remember that a margin is outside of the border, as a rule and before the padding starts, if you have any padding.

Where this comes into play the most is with creating a display table, and although the display type for table in css is not fully implemented at this time you can redefine the table, th, tr, and td tags for borders, padding, and margins. With CSS you can give the whole table a border, you can give the THEAD a larger font and center the text, you can give the Header Row an accent color, a border and bolder font, and you can give the data cells a different font size, align the text, add a border, etc. You can also use a border-collapse declaration so the intersecting borders will not be repeated. You can use border-spacing to put a defined width space between the data cells. You can even use the caption-side declaration to specify if you want the caption on the top or bottom of the rows of data.

Another problem for html developers has always been how to get a formatted table cell if the cell contains no data. CSS has helped solve this with the empty-cell declaration. You can specify either show, hide or inherit. If you select show you will still get the background and borders if you select hide you will not see them.

Backgrounds and Images

Background colors, shading, and images are the things that really can make a website or web application stand out. With a few well selected colors and graphics you can take a site from plain black text on white to…well the sky is the limit. The secret to success is in careful planning and selection of the graphics, and the application of styles and elements that compliment those selections. Here are some good examples of pages using CSS:

CSS Zen Garden – Bugs http://csszengarden.com/?cssfile=/157/157.css&page=1

CSS Zen Garden – Greece

http://csszengarden.com/?cssfile=/169/169.css&page=1

Eric Meyer Web http://meyerweb.com/

Lazy Day in Kansas http://www.bullfrogslive.com/KsRiverBank/

A word about designating color. You can designate color by one of three ways, the name of the color (red) the rgb values (0, 39, 0) or the hexadecimal value #C10000.

Earlier we talked about the box model and the different aspects of that model. Those aspects become very important when thinking about applying a background image to that box and placing it exactly where you want it, and also designating if the image is to repeat, and how it is to repeat. The declarations for backgrounds and images are listed below.

background-color

<color> transparent

background-image

<uri> none

Background-repeat

repeat, no-repeat, repeat-x, repeat-y

background-position

%, length, left, center, right, top, bottom,

background (shortcut)

color, image, repeat, position

If you specify a background image in the css file, the url needs to be the path that is relative to the the uploaded css file. A declaration like: p{ display:block; background-image:url(myimage.gif); background-color: yellow;} assumes that the image is available in the same directory as the css file.

Background position can be as varied as there are backgrounds. You can use the old standbys from html days of top and left and right, but to me those seem a little boring. I like to use the pixel indents or percentages to specify exactly how far in from the top and left to start the image (of course the box has to be defined as big enough to hold the entire graphic). This is done by using the numeric pair for the left and top position where the first value is the indent from the left (say 50%) and the second value is the indent from the top (say 0%). So, bottom left would be background-position:0% 100%;. If all of your paragraphs have an indent of 30 pixels and you want your banner graphic to align with the text you can set your banner graphic position to 30px 10px.

Hide Something

Sometimes you want to, for the purpose of design only, hide a textual heading or some other element, so that you can replace it with a graphic, or just not display it at all. CSS allows for this with the very useful declaration of visibility. You can set the values to either visible or hidden. This becomes very useful if you want to hide from the visual display a block of text, but make that same block of text readable by a screen reader. Here is an example of how you would accomplish that.

<div id="hideThis"> This is the some special instructions for screen reader users</div>

style sheet for media type=display: #hideThis {display:block; visibility: hidden;}

style sheet for media type=aural: #hideThis { display:block; visibility: visible;}

Resources

CSS – The Definitive Guide by Eric Meyer

CSS Zen Garden – csszengarden.com

Eric Meyer website –meyerweb.com

Adaptive Path – adaptivepath.com