Skip to main content

Learning CSS

Author: Corrie Haffly, PixelMill

PixelMill offers modular site-building solutions optimized for Web 2.0, featuring high quality templates, images, video, audio, add-ons, platform-specific solutions, training, and custom services for developers' web design needs.

This article isn't meant to give you a complete and thorough overview of CSS, but should give you a practical foundation for working with CSS in templates and learning more in the future.

Basic CSS Rules

CSS code is structured differently than HTML. You can think of CSS code as a list of rules. First you have to state what you're making the rule for (the "selector"). Then, you list out the different properties that you want to change. It's pretty simple!

selector {
      property1: value;
      property2: value;

Like with HTML, you can format CSS however you want. It can be in one long line, or split up into several lines with tabs for readability.

A selector can be an HTML element, a custom class, or a reference to an ID.

If the selector is an HTML element (such as p, h1, a, and so on), you can use it to set properties for every instance of that HTML element on the page.

The selector can also be a custom class. Custom classes can be named almost anything you want, and start with a period—.redtext,.nomargin, and.bigheading are all examples of classes. In the HTML code, you can apply these classes with the class attribute, like this: <h1 class="redtext">. Classes can be applied as many times as you would like.

The selector can also refer to an ID on the page. IDs are unique, so unlike a class, which can be applied multiple times, the ID's definition would only apply to the element on the page with that ID. For example, let's say that you have a heading with an ID in the HTML code like this: <h1 id="title">. In the style sheet, you reference the ID by adding a number sign (#) in front of the ID name, like this: #title. This would be the selector for the rule.

Here are some code samples from a sample style sheet:

body {
      margin: 0px;
      padding: 10px;
      color: #666666;
      font: 11px Verdana, Arial, Helvetica;

(This rule is for the body element, and would therefore apply to everything inside the body. So the default text color is grey, and the default text size and font are 11px Verdana. This saves having to set the text color and font for every single element on the page!)

h1 {
      font-size: 24px;
      color: #003399;

(This rule for Heading 1 overrides the body rule because it comes later in the style sheet. So Heading 1 has a different color and is larger than the normal text on a page.)

.redtext {
      color: #ff0000;

(This is a custom class created in the style sheet for red text. I could apply this to anything—a paragraph or a heading—and it would override the default font color.)

#title {
      color: #000000;
      border-bottom: solid 1px #000000;

(This is specific to an ID on the page. Presumably I have a heading on the page with the ID of "title." This rule would turn the text black and add a black border on the bottom.)

Text Formatting with CSS

Now that you know how a style sheet is structured, let's move on to the various options for text formatting.
Here is a list of commonly-used properties that affect text:

  • color: Set this to a hexadecimal value or a color name.
  • font-weight: Usually this will be normalor bold, although there are other values as well.
  • font-style: Set this to normalor italic.
  • font-size: This is usually set to an em, percentage, pixels, or points. Em is similar to percentages, except that they are expressed in decimals with 1 = 100% (for example, .7em instead of 70%). Both ems and percentages allow for resizable text.
  • font-family: List the font family or generic names, separated by commas. If a font is two words or more, enclose it in quotation marks—for example, Georgia, "Times New Roman", Times, serif.
  • You can list the above styles in shorthand notation like this:
    font: bold italic 120% Verdana, Arial, Helvetica, sans-serif;
  • text-align: Set this to left, right, center, or justify.
  • text-transform: This affects the letters in your text, no matter how you have typed them! You can set all the words to belowercaseor uppercase, or just capitalizethe first letters.
  • text-decoration: This is how you can remove the underline from links. Set it to none (to remove the underline), underline, overline, or line-through.
  • letter-spacing: Increase the space in between characters by adding an amount. For example, letter-spacing: 2px;
  • line-height: Increase the space in between lines, as well. For example,line-height: 110%;

Style Sheet Code Examples

Here are some common examples of text formatting that you might see in a style sheet. I am going to use this chance to also show you more ways that CSS rules can be defined.

Setting link colors and underline effects

a:link { color: #ff0000; text-decoration: none; }
a:visited { color: #990000; text-decoration: none; }
a:active, a:hover { text-decoration: underline; }

This code sets the link and visited link colors to be red (and slightly darker red). The "active" and "hover" states of the link are then set to show an underline when you mouse over the link or click on the link.

Setting a property for multiple selectors

h1, h2, h3, h4, h5, h6 { color: #00cc99; font-family: Arial, serif; }

The above code illustrates a nice function of CSS—if you want to set a property for multiple selectors, you can list all of the selectors, separated by commas. So all of the headings would be set to the same color and font.

Here is one example of how I might choose to set headings in a style sheet:

h1, h2, h3, h4, h5, h6 {
      color: #003399;
      font-weight: bold;
      font-family: Arial, serif;
h2, h4, h6 { font-style: italic; }
h1, h2 { font-size: 150%; }
h3, h4 { font-size: 130%; }
h5, h6 { font-size: 110%; }

This might display in a browser like this:

Heading 1
Heading 2
Heading 3
Heading 4
Heading 5
Heading 6

Setting properties for elements within specific areas

#leftcolumn p { color: #ffffff; }
#rightcolumn p { color: #000000; }

This code illustrates a situation where the page has two columns that are different colors (and, of course, we've defined the left and right columns to have IDs in the HTML code). Let's say that in this example, the left column has a dark background, while the right column has a light background. Text that is readable in one would be unreadable in the other. So, the code above says "any paragraph text in the leftcolumn ID should be white, while any paragraph text in the rightcolumn ID should be black."

As another example of how this could work, the code below would only affect second-level bulleted lists in the left column:

#leftcolumn ul ul { font-style: italic; }

CSS Boxes

Let's get a little more complicated with some CSS "boxes." First, you can think of block-level elements like paragraphs and headings as taking up an area on the page shaped like a box. This is a little more obvious when we add properties that affect the background color and border of the element. Take, for example, this CSS code below:

p { background: #ccccff; border: solid 1px #666699; }
h1 { background: #ccff99; }

If this were actually applied to a web page, the page would look like this:

Notice that the "box" stretches all the way across the area of the browser window, no matter how short or long the heading or paragraph is.
You can play with these boxes using CSS properties.

  • width and height: Use a percentage or pixel amount to set the width and height of a block element. (If the text is taller than the height can handle, different browsers will do different things with it.)
  • background-color: Sets the background color of an area. Use a hexadecimal color code or an HTML color name.
  • background-image: Sets the background image for an area. Use the formaturl('imagefilename.jpg')for specifying the image.
  • background-position: Sets the starting position for a background image. Use top left, top center, top right, center left, center center, center right, bottom left, bottom center, bottom right, or percentage and pixel values for horizontal position and then vertical position, like this: 30px 50px(30 pixels from the left, 50 pixels down). Negative values can be used as well.
  • background-repeat: Sets how the background repeats. Use repeat-x for repeating horizontally, repeat-y for repeating vertically, repeatfor both horizontal and vertical (default), or no-repeat.
  • background-attachment: Set to fixed to keep the background image from scrolling.
  • You can list the background rules in shorthand notation like this:
    background: #ff0000 url(‘background.jpg') no-repeat 10px -2px;
  • border-bottom-width, border-top-width, border-left-width, border-right-width: Sets the width of a border. Use thin, medium, thick, or a pixel value for the thickness.
  • border-bottom-color, border-top-color, border-left-color, border-right-color: Set to a hexadecimal color code.
  • border-bottom-style, border-top-style, border-left-style, border-right-style: Common settings are none (for no border), solid, dotted, or dashed.
  • There are lots of ways to write the border values in shorthand:
    border-top: solid 1px #ff0000;—write the values in shorthand for each side.
    border-width: 0px 1px 3px 1px;—define border values for all sides at once (top, left, bottom, right).
    border: solid 1px #000099;—define the border for all sides at once.
  • padding-left, padding-right, padding-bottom, padding-top: Set these to an amount (pixels or percentage) to affect the space in between the content and border. Set them all at once with the shorthand notation:
    padding: topvalue rightvalue bottomvalue leftvalue;
    For example: padding: 10px 5px 8px 5px;
    If you just have one value, it will set the padding for all sides.
  • margin-left, margin-right, margin-top, margin-bottom: Set these to an amount (pixels or percentage) to affect the space outside of the border. Some browsers may "collapse" this space; if there are two boxes that both have margins, it will space them apart by the larger margin. Similar to padding, you can use shorthand notation:
    margin: topvalue rightvalue bottomvalue leftvalue;

CSS can get a little more complicated when you combine widths and heights with padding and borders. The diagram below illustrates the CSS "box model," which determines how browsers should treat the dimensions of a box.

The width property defines the actual area that the content will fit inside, and padding, border, and marginamounts are added on outside of the width. (You can see that a width of 100% with padding and border values would be problematic... so watch your values carefully!)

The Box Model Hack

You might see code in templates that looks something like this:

selector {
      width: 300px;
      height: 200px;
      padding: 10px;
      /* box model hack */
      voice-family: "\"}\"";
      width: 280px;
      height: 180px;
html>body selector { width: 280px; height: 180px; }

There are three widths and heights, plus some funny-looking code. This is called the "box model hack." Current browsers will do the right thing with your dimensions, paddings, margins, and borders as described above. However, Internet Explorer 5 interprets the box model incorrectly by taking the width to be the total width, then subtracting the padding and border to give you the remaining content area width. So the exact same code below would look different in Internet Explorer 5 and other current browsers:

selector {
      width: 280px;
      height: 180px;
      padding: 10px;

The diagram on the left shows the correct rendering of the code, while the diagram on the right shows how Internet Explorer 5 messed up the dimensions of the box:

In order to get the code to work for both Internet Explorer 5 and current browsers, many developers use the Box Model Hack, which involves this code:

voice-family: "\"}\"";

This code causes Internet Explorer 5 to ignore what comes after it. So in the code below, Internet Explorer 5 and current browsers such as Firefox and Internet Explorer 6 look at the first width and height (300px by 200px). The padding is then applied. When Internet Explorer 5 hits the box model hack, it ignores the rest and moves on. Other browsers aren't confused by that, so they see the second width and height (280px by 180px) and use those dimensions as the correct dimensions. The last line of code is a special line of code to allow the Opera browser to have the proper dimension as well, because Opera acts like Internet Explorer 5 and ignores what comes after the box model hack.

selector {
      width: 300px;
      height: 200px;
      padding: 10px;
      /* box model hack */
      voice-family: "\"}\"";
      width: 280px;
      height: 180px;
html>body selector { width: 280px; height: 180px; }

CSS Positioning

Understanding how to use CSS to create layouts is the last step to mastering changes in CSS templates. There are lots of resources online and in books to teach you how to use CSS to make your own layouts, so I'll focus this part of the article on the types of CSS techniques for layout that you might see in templates and how to tweak them.

Layouts with DIV

Instead of using tables and table cells to create columns, CSS templates use the divelement in the HTML to divide the content into sections and then format the divin the style sheet. Pulling apart a CSS template will often yield structural code such as:

<div id="toprow">...</div>
<div id="threecolumns">
      <div id="leftcolumn">...</div>
      <div id="centercolumn">...</div>
      <div id="rightcolumn">...</div>
<div id="footerrow">...</div>

Of course, those div s may have different ID names, but the concept is the same. Developers name the IDs differently; sometimes it may be easy to tell what a certain div is for, but other times the name may be ambiguous. Either way, it is a good idea to look in the style sheet to figure out the display properties of the div.

A DIV "row"

If a div doesn't have a width defined, it's very likely that the div simply acts as a "row." The div may have a height defined. If it does, keep in mind that certain browsers such as Firefox will keep that row at the height even if the text or content is longer. The text or content will just spill outside of the div and overlap other stuff on the page. Internet Explorer, however, will resize the height automatically to fit whatever is inside. If you need to, modify the height to make room for your content.

A DIV "column"

A div column will usually have a width defined. However, there are several different ways to position the columns on the page.

One common way to get columns is to use the float property in adiv . If one divhas the float property set to left or right, the divwill be pushed to the left or right of the page with the rest of the content wrapping around it. When you have multiple divs with the width defined and set to float to the left, you will get a column format. This technique is usually used with static-width layouts (layouts that don't resize with the browser window). Here is one example of style sheet code that would format the sample HTML code from above into a three column layout:

#leftcolumn { width: 200px; float: left; }
#centercolumn { width: 400px; float: left; }
#rightcolumn { width: 150px; float: left; }

A variation of this technique with two-column layouts is to have one column float to the left and the other column float to the right.

With this float technique, you will often find that the developer creates "faux column" effects by using a repeating background image in the div that contains the three columns (#threecolumns in the code above). This may confuse you if you look in the HTML code or CSS code expecting to be able to change the colors of the columns—in reality, the column effect may have been produced with a repeating image. You'll have to edit the column background image in an image editor if you want to modify the colors. Here's what the style sheet code might look like for that section:

#threecolumns { background: url(‘columnbackground.gif') repeat-y; }

Another way to achieve columns is to have a main column with large borders on the left and right, and the side columns positioned with negative margins to "overlap" the main column's borders. This technique is usually used for liquid, or resizable, layouts. The code for this effect is usually quite complicated—below is a sample of simplified code to help you recognize it:

#threecolumns { border-left: solid 200px #cccccc; border-right: solid 200px #eeeeee; }
#leftcolumn { width: 200px; float: left; margin-left: -200px; }
#centercolumn { float: left; width: 100%; }
#rightcolumn { width: 200px; float: left; margin-right: -200px; }

(The code above will NOT work on its own—it's just meant to help you recognize this type of layout! See or search for "CSS liquid layouts" in a search engine for more information about creating your own liquid layouts.)

Another common technique for column layouts is to utilize absolute positioning. This is also used with liquid layouts. The general idea of this technique is to have the center column with large borders or margins on the right or left, and then have the left and right columns absolutely positioned in the resultant empty space. Adding the position: absolute; property will take the div out of the "flow" of the page and stick it anywhere you want using the top,left,right, orbottom properties to position it. Here is one example of a style sheet that uses this method:

#centercolumn { margin-left: 200px; margin-right: 200px; }
#leftcolumn { width: 200px; position: absolute; top: 0px; left: 0px; }
#rightcolumn { width: 200px; position: absolute: top: 0px; right: 0px; }

Other Common Tricks

Here are some other CSS layout tricks that you may see in templates, and why they are there.

<br class="clear" />
You'll often see this code after the column divs in a layout. This allows Firefox to display any column background images (in "faux columns" as described earlier) or background colors that are part of the outer wrapping div (#threecolumns in the example from earlier).

margin: 0px auto;
This code usually shows up in elements that are meant to be centered. There is a bug in Firefox that doesn't center elements properly even if the outer element has text-align: center; defined. Adding the line of code above will force Firefox to center the element.

This code makes what would normally be a block element behave like an inline element. For example, usually list items take up their own "block" of space. If you add display: inline; to the li element style definition, all the list items will line up next to each other. You'll see this code where a bulleted list is being displayed horizontally for things like horizontal navigation links.

display: block;
This code, as you might guess, makes what would normally be an inline element behave like a block element. For example, you can turn hyperlink elements into block elements to control the dimensions (width and height). This is frequently done to navigation links that look like buttons.

@import url(‘styles.css');
<link rel="stylesheet" type="text/css" href="styles.css" />

The two lines of code above represent different ways that a style sheet can be loaded to an HTML page. The @import code is often used for sites that are trying to hide style sheet code from Netscape 4. However, many templates will use the<link> tag because FrontPage doesn't update the URL in @import if you move pages into subfolders.

Learning More CSS

There are many resources both online and offline to help you expand your knowledge of CSS. Here are a couple of links that make it easy for you to get more information.

Next: Transitioning to Accessibility

Articles in this series

  1. Transitioning to XHTML Strict in 10 Steps
  2. Transitioning to Semantic Markup
  3. Transitioning to CSS
  4. Learning CSS [this article]
  5. Transitioning to Accessibility
  6. Transitioning to Expression Web

Related Links