Introducting CSS3 Colors

Defining colors in red, green and blue is supported by CSS3 in several ways.

Hexadecimal Values

You can declare the hexadecimal value of your red, green and blue with hexadecimal values ranging from 0 to 255 in the format of 00 to FF, put the three together preceded by a hash (#), and that’s the color. For example, #FFFFFF for complete saturation of red, green and blue comes out white, #000000 for lack of any color comes out black. A mix and match of hexadecimal values from 0-255 using any two characters A-F0-9, case insensitive, for the red green and blue values, combined together in the order of red, green and blue can create millions of colors.

Did I mention case-insensitivity? It doesn’t matter if you use #FFCC00 or #ffcc00 – the value syntax is case insensitive.

The RGB hexadecimal notation also has a shorthand, of #RGB, where the R, G, and B are a single character, A-F0-9, case insensitive, put together, preceded by a hash mark. Identical to the long format, the browser expands the RGB value, such as #369 to #336699.

All browsers support all of the hexadecimal values, both short hand and long hand. There used to be a discussion of web-safe colors. Web face colors has been a non-issue, even for hand held devices. It is safe to use any color combination (may not be pretty or legible, but it will render).

rgb() syntax

Instead of using the hexadecimal values for RGB, you can use the base 10 value for your mix of red, green and blue, or even percentages. Instead of preceding your color with a hash tag, the syntax is the keyterm ‘rgb’ follow by your comma-separated values in parenthesis.

#FFFFFF = #FFF = rgb(255, 255, 255) = rgb(100%, 100%, 100%).

All browsers support all of the RGB color combinations in general. Some browsers allow the mixing of rgb() numbers with percents, but the specifications clearly state that this is not expected behavior, and not all browsers support it, so avoid mixing value types.

What’s new?

New in CSS3 is RGBA. RGBA is similar to RGB, but with an added A for AlphaTransparency. The rgb() specifications were extended in CSS3 to include ‘alpha’ to allow specification of the opacity of a color. The first three values are still red, green, blue. Thee fourth value is the opacity level, 1 being fully opaque, 0 being fully transparent, and any float being everything in-between.

rgb(255, 255, 255) = rgb(100%, 100%, 100%) = rgba(255, 255, 255, 1)

The above are all equal to white, since 1 means fully opaque. But don’t get confused: rgba(0,0,0,0) is transparent, not black, because the level of opacity is none.

Unlike RGB, there is no hexadecimal notation for RGBA. Unlike RGB, the IEs don’t understand RGBA. IE8 correctly ignores properties with rgba() in the value. IE6 and IE7 overwrite values, without understanding them, and generally inherit the default value when confused.

RGBA is going to be extremely useful as drop shadows on boxes and text become better supported. While it is very common to see text-shadow: 3px 3px 3px #CCCCCC; or text-shadow: 3px 3px 3px #000000;— including a gray or black shadow, the effect looks much better if you write text-shadow: 3px 3px 3px rgba(0, 0, 0, 0.4); While the color #CCCCCC and rgba(0,0,0,0.4) look similar when solid over a white background, when included as a shadow, the #CCCCCC starts off as a solid grey, which looks a little off. The RGBA color is always translucent, which looks MUCH better.

Hue, Saturation and Lightness

HSL stands for hue, saturation and lightness. The HSL format simplifies color palette creation as you can pick a hue as the base, then manipulate the lightness/darkness and saturation of the hue selected.

HSL is a new color type added in CSS3, standing for hue, saturation and lightness. The syntax is similar to rgb(), but instead of including the values for red, green and blue, the color value accepts values in degrees from 0 to 359 for hue, and percentages for saturation and lightness, with 50% being the norm for lightness and 100% being the norm for saturation.

Lightness of 0% will be white, 50% will be the actual hue, and 100% will be black. Saturation of 100% will be the hue, and saturation of 0 will give you a shade of gray from white to #808080 to black depending on the lightness.

Up Next

In part 2, we’ll cover hsl and hsla in greater depth.

Introducing @font-face

@font-face, a feature that has been talked about since 1998, is finally here! Nope, it’s not a twitter ID. @font-face is a component of CSS3 that allows the designer/developer of a web site to include fonts that are not installed on the user’s computer.

Web site design has been hampered by the limited number of fonts available to most clients. Designers have been using image replacement and methods such as sIFR and Cufón to make up for limited choices in typography. If designers want to ensure their designs look almost identical for all users, they’re limited to the few font sources that are known to be installed on almost all computers.

Wait. Let’s make that sentence past tense. “If designers wanted to ensure their designs looked almost identical for all users, they were limited to the few font sources that were known to be installed on almost all computers.” There is now a solution! We are no longer limited to Arial, Helvetica, Georgia, sans-serif!

@font-face enables the developer/designer to use any (with legal limits) font family on a web site by downloading the font file onto to client computer, and then declaring it as you would any font-family.

@font-face has been supported to some extent for years. It was in the CSS2 specifications. Microsoft implemented @font-face in Internet Explorer 4, but, as is typical of Microsoft, used a proprietary font format format (EOT). Due to copyright and legal issues, @font-face was dropped in the CSS2.1 specification. But, now it’s back. And it’s supported. It is expected to be in the W3C CSS3 specification when that finally gets finalized. Assuming that it will be in the CSS3 specification, all other browsers (Opera, Webkit, Mozilla) support @font-face with an implementation that supports formats like TTF and OTF. IE continues to support only the EOT format. Webkit for mobile (think ‘iPhone’) supports only SVG.

There are two steps to using the font of your choosing in your CSS file: 1) you must first declare your intention to import a font by using the @font-family syntax, telling the browser how you are going to reference the font (what name you will use to refer to the font), where to download the file, and what format the font is in. 2) You then have to include the font name in a font-family declaration, just as you would include Helvetica, Georgia or "Times New Roman".

The syntax for the @font-face implementation is:

@font-face {
  font-family: yourNameForTheFont; /* required */
  src: source;						/* required */
  font-weight: weight;				/* optional */
  font-style: style;				/* optional */
}

The source takes both the file name source and the format type. The source can take several formats. In addition, you can declare more than one source. If the browser doesn’t find the first source, it will go for the next source, and so on, until it either finds a source, or it runs out of sources. As withe all CSS file references, the URL should be a relative or absolute path. If relative, it should be relative to the CSS file.

Example formats include:

@face-font {
     font-family: 'My Font Name'
     src: url('../fonts/makeUpSomethingElse.eot');
     src: local('Edwardian Script ITC'),
          url('../fonts/EdwrdScrpItc') format('opentype'),
          url('../fonts/GaelicWimsy') format('svg'),
          url(data:font/otf;base64,T1RUTMillIONsOfLETteRsInaROW12fAtGrrYUUUUBx);
}

It is not enough to declare the creation of the font. You have to use it. Once you’ve downloaded the font and assigned it a font-family name, you can use that name as you would any other font name as the value of the font-family property

.mySelector {
    font-family: 'My Font Name', Arial, Helvetica, sans-serif;
}

Hurdles to consider when considering implementing @font-face

Yes, @font-face is finally supported in all browsers. But implementation isn’t so simple. There are several hurdles to consider and overcome to ensure that your implementation works, looks good, provides a good user experience and is all legal:

  1. Different formats for different rendering engines and devices

    While all browsers support @font-face to some extent, we still have browser support and compatibility issues to contend with. Most modern browsers support both the TTF and the OTF format. Firefox 3.6+ supports WOFF, a web-only font format. As mentioned earlier, Safari for iPhone only accepts the SVG format. And, we’re stuck with IE only accepting the EOT file format. There are also some rendering differences in those various formats.

  2. Huge file sizes

    Though not exactly a hurdle to implementation, font file sizes are a concern to keep in mind when it comes to user experience. Font files can be huge. Some formats are way larger than others. An embedded font means you have to download to use. A source with simple lines, like Arial or Helvetica, may weigh about 16 – 20kB. More complex fonts, with complex strokes, that you’re more likely to want to include, may be over 200kB in file weight. And remember that you may need to download the bold, italic and bold-italic versions of your font

     

  3. Delay in rendering

    Depending on the file size of your font file, and whether the font is already cached in the client browser, embedding fonts can cause the browser to rewrite the page. In our above code example, the page may render with Arial, Helvetica or other sans-serif font, then redraw the page when the font file is successfully downloaded.

    Embedded fonts do not always show immediately . The delay in rendering depends on the browser and whether the fonts have been loaded in cache or not. As such, text with embedded fonts as the font family may take a moment to display or display first with a system font, as the embedded font is loaded.

  4. Legal implications of font usage

    To allow the downloading of a font, you must have a web-font license for the font! It’s not enough that you purchased a font and have a right to use it for personal use with any application on your own computer, including production of print material for distribution. You have to have a license or other permission to distribute the font file itself, since, in effect, this is what you are doing with @font-face. Check the Web site you are downloading or purchasing the font from, or the documentation that comes with the font. Only embed fonts that have the appropriate licenses.

Not a hurdle, but something to be aware of:

For security reasons, some browsers (like Safari) ask the users if they are alright with downloading fonts from the internet – so that is a user experience consideration as well.

Tips for @Font-Face

  1. Fallbacks for browsers that don’t support @font-face: Depending on what font you choose, your default fonts may not look right at that font-size. Using Modernizr can be helpful in controlling the appearance when @font-face is not supported. For example, if you use an expanded font, such as Impact, or a very condensed font, fallback fonts such as Arial or Verdana can break your layout. With Mondernizr you can tell the browser to user larger or smaller font-sized if the browser doesn’t support @font-face, or even tell the browser to user sIFR, Cufon or any image replacement method for non supporting browsers only.

    .fontface  h1 {
      font: 16px/24px 'My Font Name', Arial, Helvetica, sans-serif;
    }
    .no-fontface  h1 {/*
      Rules for sIFR/Cufon or for an image replacement method of your choice, or a better font size for Arial and Helvetica.
    */}
    .no-fontface  h1#myID {
    	background-image: url(imagereplacement);
    }
    
  2. Include default fonts in every font declaration: Do not forget to include default fonts in your font-family declaration. Puts the declared font-family name of your downloaded @font-face embedded source, and follow it with the default alternatives (arial, helvetica, sans-serif).

  3. Include font variants only if needed, but do include them if used: Check which variants of the font you need for your site. Include the italic, bold and italic bold font if you are going to use it. But don’t included more than you have to! You don’t want the user to have to wait for the download of a font if that font is going to be unused.
  4. Check out the following resources:

Clearing Floats

The most widely used method of clearing floats uses the addition of an element, generally a <br class="clearfix" />, to clear both left and right. While it is the most ubiquitous method, even included in the Adobe Dreamweaver CS3 templates.

.brclear { 
     clear:both; 
     height:0; 
     margin:0;
     font-size: 1px;
     line-height: 0;
}

Listing 1: CSS from the Dreamweaver template CSS.

These fixes use a break with the classes of .brclear and .clearfix respectively in the markup as a clearing element. This fix works great: the CSS provided ensures that the break does not disturb the layout by taking up any space on the page. Yes, it works great, but it has two major problems:

  1. The addition of non-semantic, purely presentational elements to the HTML
  2. The inclusion of a <br> to your code inhibits you from not breaking should your design change.

While it’s not "illegal" to include non-semantic code, my argument has always been "<br> is only for poetry," and I avoid using it other than to intentionally break a paragraph into two lines for semantic reasons. There are several ways of clearing a float *without* adding a <br> to clear your float. In this tutorial, we’ll go over these four.

  1. Clearing the next element
  2. Floating the parent container
  3. overflow: hidden
  4. Generated content

Because of cross browser issues, and for general markup reasons, different methods are more appropriate for certain situations. We will cover several issues, but not all. Think of this as a guide, not a rule book, for clearing floats.

Clearing the next element

The easiest way to clear a float is to add a clear to the next element in your mark up.

<div class="floatLeft">content...</div>
<div class="floatLeft">content...</div>
<div class="floatLeft clearBoth">content ...</div>
 
.floatLeft {
     width: 33%;
     float: left;
}
.clearBoth {
     clear: both;
}

Listing 2: Clearing via the next element in the page.

This is the simplest method, and great for simple float clearing. In listing 1, all the div’s are one-third of the width of the parent element. We clear on the third div. Had we not cleared the third div, the three divs would have all been on one line, taking up only 99% of the parent element’s width.

Note that this is just an example. The div with the clearBoth class could have been any element coming after the last floated element, and could have had any class name, as long as the class had the property/value of clear: both; in your CSS. I used these class names to make it more obvious what we were trying to achieve. It is recommended to *not* use class names based on appearance, and to opt for class names based on function.

This method works most of the time, and is an easy solution that keeps you from adding a bunch of non-semantic elements simply to clear floats. However, it doesn’t work for everything you may want to do. When you float an element, and then clear an element with another floated element, as we did in Listing 2, the cleared element will drop to the next line, but the parent element will not grow to encompass your floated element unless you also float the parent (more on floating the parent below). If your clearing element is not floated, this method does work.

And, of course, there are bugs with both floating and clearing floats in IE6 and IE7. Bugs include a bug in IE7 where a non-floated element with a width will overlap a floated element within a non floated element that has a height declared; a bug in IE7 where the margin-top of the non-floated clearing element will be added to the margin bottom of the element it is clearing; and a bug in IE6 where the floated element will flash on and off the screen.

Although floating the next element may not work for every float you want to clear — especially if your float is the last element on the page, or if it causes one of the numerous bugs — it works in many situations, and is simple to implement. In practice, I tend to add {clear: both;} to main sections of my page, such as on my #topnavigation, #content and #footer divs.

Floating the parent container

To clear a float, you can float the parent element, as long as the parent has a total width equal to 100% of the width of the page or it’s own parent. The floated element will be at least as tall as it’s tallest floated child. And, since it has a width of 100%, the next element on the page will automatically be cleared.

To understand the importance of the W3C rule that a floated element is at least as tall as the tallest floated element contained within it, you need to understand the basic of floats.

A float is an element that is laid out according to the normal flow, then taken out of the flow and shifted to the left (if floated left) or right (if floated right) as far as possible. When you float an inline element it becomes a block. Content can flow down the right side of a left-floated element and down the left side of a right-floated element, unless prohibited from doing so by the “clear” property, or because the width of a float is 100%. Floated elements will move to the left or right until their outer edge touches the containing block edge or the outer edge of another float. The top of a floated element will be at the same level as the float next to it, if there is enough room, or at the bottom of the preceding block if the element was originally inline. If there isn’t enough room on the current line for the floated box, it will move down, line by line, until a line has room for the float. (If two floats don’t appear to start on the same line, it is usually because the padding is different.)

Because a floated element is no longer in the normal flow of the document, non-positioned block boxes created before and after the float box flow vertically as if the float didn’t exist. If a parent or containing element only contains floats, the parent element will have no height, as if it were empty. … A float can overlap other boxes in the normal flow. [If you float the parent] give it a width, or it will shrink to be as narrow as possible.

IE8: The Good: CSS 2.1 Selector Support in Internet Explorer

Internet Explorer 8, IE8, was released on March 19, 2009. Depending on your statistics source, as of July 2009, IE8 already has 17.8% of the browser market share. In the last section we provided an overview of what is new, good, bad and different in IE8. In this article, we take a deeper look at CSS 2.1 support in the IE8 browser, and compare IE8’s CSS support to IE6 and IE7.

CSS 2.1 Support

As mentioned in the overview, IE8 has complete support for CSS2.1. IE8 is the first browser to support all of the W3C CSS2.1 specifications, and currently has the best support of any browser (including Firefox, Safari and Opera) of the CSS 2.1 specifications. One may think (though no one outside of Microsoft does) that this makes IE8 the best browser, but it doesn’t. IE8 may be the first IE to support CSS 2.1, but Firefox, Safari, and Opera have already moved on to supporting features proposed in CSS3.

Internet Explorer 8 supports all CSS 2.1 Selectors

By having complete support for CSS 2.1, IE8 has a lot of improvements over IE7 and IE6 in terms of CSS support. Below are listed all the individual CSS2.1 selectors, with a brief explanation of how IE6, IE7 and IE8 compare. You’ll note that IE8 supports ALL of the selectors listed. While not shown in this grid, Firefox, Opera and Safari all support all the CSS 2.1 selectors, and have been doing so since previous releases.

By having complete support for CSS 2.1, IE8 has a lot of improvements over IE7 and IE6 in terms of CSS support. Let’s look at the differences:

Browser
Pattern Meaning IE6 IE7 IE8
E:active

E:hover

E:focus

Dynamic pseudo-classes are generally thought to be applicable to links and form elements since IE6 and IE7 don’t support them on other elements. IE8 supports pseudo classes correctly on ALL the elements.

Δ Δ
Δ Δ
Χ Χ
E:before

E:after

The ‘:before’ and ‘:after’ pseudo-elements can be used to insert generated content before or after an element’s content. Completely ignored by IE6 and IE7, it is supported by IE8. See generated content

Χ Χ
Χ Χ
*

Universal Selector: any element *{}. While all browsers support this selector, it’s best to use it sparingly if at all.

E

Type or Element selector: a specific element, such a p, td, ol {}

.class

Class selector: a class or several classes, such as: .myClass {}

IE6 does not support dual class names. For example, .one.two {} will target <p class="one two"> in all modern browsers, except IE6, which ignores it. Except for this exception, class selectors are supported by all browsers.

Δ
#id

ID Selector: Matches an element based on it’s ID: #myId {} Supported by all browsers

E F

Descendant selector: Matches any element F that is a child of element E

E > F

Child Combinator: Matches element F that is the first element child of element E

Χ
E + F

Adjacent simbling selector: Matches element F that is a the next sibling of element E. label input {} will match any input that follows a label such as <label>a label</label><input type="text">.

Note that there is a sibling selector – E~F – in CSS3 that is supported by IE7 and IE8, but not IE6

Χ
E[attr]

Attribute Selector: Matches if the element matched has the attribute: input[type] {}.

The exception to the support is that the browsers won’t match the element that has the attribute if the attribute value is empty

Χ
E[attr=val]

Attribute Selector: Matches if the element matched has the attribute: input[type=checkbox] {}.

Χ
E[attr~=val]

Attribute Selector: Matches if the element matched has the value of the attribute value: a[rel~=nofollow] {} should match <a href="..." rel="noindex nofollow">.

Χ Δ
E[attr|=val]

Attribute Selector: Matches if the element matched has the attribute with the value has atleast the val as part of the value: div[lang|=en] should match <div lang="en-us">

Χ Δ
E :first-child

The CSS selector should match the inner div element, because it is the first child of the outer div element Comments are not elements, so they should not be considered when determining the first child.

Χ Δ
E:link

Non visited link (non included above with pseudo classes since only links can be links)

E:visited

Visited link (not included above with pseudo classes since only links can be visited)

E:lang()

Matches element of type E if it is in (human) language c (the document language specifies how language is determined).

Χ Χ
E:first-letter

First letter pseudo-element: Matches the first letter of the element E.

E:first-line

First-line pseudo-element: Applicable to block-level elements, inline-block, table-caption or a table-cell, targets the contents of the first formatted line of a element.

Note that Opera 9.6, Firefox and Safari all support all of the above CSS selectors.

Legend
Full Support
Χ No Support
Δ Some support, but not full support

IE support of :hover pseudoclass

The :hover pseudo-class enables you to alter the presentation of an element when the user mouses over the element. For example, similar to Excel, you can change the color of a table row when the user mouses over a table rows using only CSS. IE6 and IE7, only support the :hover pseudoclass on links (the <a> tag) and some form elements. One very popular use of the hovering is drop down menus. In the past, because of IE6 and IE7, javascript had to be added to make sub-navigation appear on hover in those browsers. IE8, like all other standards compliant browsers, now supports the :hover pseudoclass on all displayed elements.

IE support of :before and :after pseudo-elements

The :before and :after pseudo elements enable you to add content before and/or after specified elements. For example, you can add special characters in front of list items, thereby not limiting yourself to the limited number of default list-style-types. IE6 and IE7 have no support for these pseudo-elements. IE8, however, has fully compliant support for these pseudo-elements. In fact, IE8 has better support for the content property of these pseudo elements than any other browser: better support even than Firefox.

Using differences in CSS selctor support to target browsers

Users of Community MX are encouraged to use conditional comments to target different versions of Internet Explorer. You can also use CSS selectors to target specific browsers. IE6 and IE7 have limited support for CSS 2.1 selectors. IE8 supports all of CSS 2.1 selectors, but very limited support fo CSS 3 selectors. On the other hand, all other non-IE grade-A browsers have support of several CSS 3 selectors. You can use these difference to your advantage to target specific browsers. In the last section, we provided one hack:

p.myclass {
color: green; /* all browsers */
}
body:first-child p.myclass { /* IE8 and all CSS 2.1 compliant browsers */
color: blue;
} body:last-child p.myclass { /* CSS 3 supportive browsers */
color: red;
}

This IE8 CSS filter targets all browsers with a regular element.className selector to target all paragraphs with the myClass class. It then targets all CSS2 compliant browsers with the CSS2.1 pseudo-class. It then filters out IE8 but using CSS3 to target all modern, non-IE browsers. It’s best not to use it, but it is important to understand how CSS can be used to filter browsers so you can follow other people’s code.

Up Next

In this section of IE8: the good, the bad, the ugly (and pretty), we’ve covered IE Support for CSS selectors. In the next section wel will look at IE’s support of CSS 2.1 properties and values of interest.

::before and ::after: Generating Content

In this section we learn about the different types of content that we can generated with CSS using the content property and its various value types. You’ve likely only touched upon the CSS content property, adding a simple string before or after an element. The content property can take many more values that just a simple string: you can add text, images, quotes, special characters, even images to your page using the content property to generate content in your :before and :after pseudo-elements. In this section we take a deeper look into the various values of the CSS content property.

Generated content is now supported in IE8 and all other modern browsers, so it makes sense to learn. There is an archaic table of browser support for the various values of the content property below (see listing 8).

Values of the CSS content property

The CSS content property can take as its value

  • none
  • normal
  • <string>
  • url
  • open-quote
  • close-quote
  • no-open-quote
  • no-close-quote
  • attr(attribute)
  • counter(name[, style]).

In this section of the series, we will discuss all of these values. We will only touch upon attr(attribute) and counter(name) in this section, as we will dive deeply into those two value options in the next section of this series..

Definition and purpose of each value of the content property

The CSS content property can take as its value none | normal | <string> | url | open-quote | close-quote | no-open-quote | no-close-quote | attr(attribute) | counter(name[, style]). Values have the following meanings:

  • content: none;

    none: When content: none; is included, the pseudo-element is not generated. This does NOT work in the current version of Safari (or Opera), nor is it expected to be supported in the next release of Safari. The solution to fix this which works in all modern browsers is to define the value as an empty string: content: "";. The two quotes with no content between the quotes is called an empty string. For example, some browsers automatically add opening and closing quotes to the <q> element. To override this default presentation, include q {content: "";} instead of q {content: none;}, so that all browsers override the default <q> presentation.

  • content: normal;

    normal: The ‘normal’ value, according to the W3C specifications, is supposed to “compute to ‘none’ for the :before and :after pseudo-elements.” To me, this specification is unclear. Is it supposed to compute to ‘none’ unless the default browser rendering includes content? The only element where interpretation of this value is relevant is the <q> or ‘quote’ element. In this case, the ‘normal’ value is handled differently in different browsers. Safari and Opera show the default content of quotes encompassing the text in between the opening and closing <q> tags. IE8 and Firefox do not show the quotes: computing to ‘none’. In the grid of support below I put support for Safari and none, and Opera as ‘iffy’, since my take is that Opera misinterpreted the deflation: Opera does compute to ‘none’ for most elements, but leaves quotes around the <q>, which is “normal”, but not the correct value for ‘normal’ according to the W3C.

  • content: "Estelle: ";
    content: "\00a3 "; /* includes '£' */

    string: The values of content can be a string encompassed in quotes. Including a string value will add your string before or after the element (depending on which pseudo-element is used). Strings can either be written with double or single quotes: the opening quote needs to be the same type of quote as the closing quote.

    If your string includes a quotation mark, make sure you escape it with a back slash. Otherwise, you can generally include any keyboard character. If you are putting a string of text, you may want to include a space in your text. You can also generate this spacing using CSS. Remember, as we learned in section 32, you can use CSS to stylize your generated text even though the generated text is NOT added to the pages document tree.

    Advanced topic: If you are going to include any non-ASCII characters or entities, declare the charset in your CSS and XHTML, and/or use the ISO / IEC 8859-1 (a.k.a. Latin-1) code for the character. Check out my blog post on including named entities in CSS and Javascript for examples and instructions.

  • content: url(myBullet.gif);

    url: You can add images as generated content (and even sound as generated content for auditory pages), by linking the content to an online file. To include an external file as generated content, include the URI inside the “url()”. The value of the property in this case it a path and file name that designates an external resource, such as an image, inside the “url()” as demonstrated above. If the browser can’t display the resource, FireFox and Internet Explorer 8 omit the file completely, as if it were not specified. Safari, on the other hand, indicates that the resource cannot be displayed with a missing image icon.

  • content: open-quote;

    open-quote and close-quote: These values are replaced by the appropriate string from the ‘quotes’ property. When including nested quotes, if the outer quotes are double quotes, generally, in literature, the inner quotes should be single quotes. The values of open-quote and close-quote are supposed to handle that scenario, but it doesn’t work cross browser. Firefox and Internet Explorer get these values right. Opera handles this, adding quotes, but does not nest quotes correctly. Safari ignores these values completely. Until Safari handles the open-quote and close-quote, values, I recommend using doing a double declaration. The first declaration should be a string with an escaped quote of your choosing. The second declaration should use the key terms of open-quote or close-quote, so the browsers that understand the declaration can nest correctly.

    p.quote:before {
       content: "\"";
       content: open-quote;
    }

    Listing 1: The first line in understood by all browsers supporting content, since all browsers support the string value. If a browser does not understand the “open-quote” value, the browser ignores the value and inherits the string value from line 1.

  • content: no-open-quote;

    no-open-quote and no-close-quote: Introduces no content, but increments ( or decrements) the level of nesting for quotes. As mentioned in the open-quote/close-quote section above, when quotes are nested in some languages, the type of quotation mark used changes depending on the level of nesting. This is when these values are relevant. Again, safari ignores the declaration. Opera, Internet Explorer 8 and Firefox get it right (though Opera doesn’t nest properly. The trick described in Listing 1 works here too, except serve an empty string, as in listing 2.

    p.quote:before {
       content: "";
       content: no-open-quote;
    }

    Listing 2: The first line in understood by all browsers supporting content, since all browsers support the string value. If a browser does not understand the “no-open-quote” value, the browser ignores the value and inherits the empty string value from line 1.

  • content: attr(title);

    attr(x): This ‘function’ returns as the content value a string with the value of the X attribute of the element on which the content attribute is applied. The attribute value will be elaborated on in the next section.

  • content: counter(subtitles, decimal);
    content: counter(headers) "." counter(subtitles) ": ";

    counter(name) or counter(name, style): The counter takes two parameters: the name, which you can reference to increment or reset, and the style, which, if not declared, defaults to “decimal”. While you can name the counter almost anything except ‘none’, ‘inherit’ or ‘initial’, avoid key terms. Counter will be elaborated on in the next section.

*By “modern browsers” I mean all browsers in listing 3 other than IE6 and IE7.

Browser support for the CSS content property and :before and :after pseudo elements

The CSS content property and possible values
IE6 IE7 IE7 in IE8 IE8 FF3 FF 3.5 Beta Saf 3.2 Saf 4 Beta Opera 9.64
:before
:after
content Since :before and :after is not supported in these browsers, testing is not possible, and moot. It is assumed that IE6 and IE7 does not support the content property, therefore supports none of these values works, except for issues below works, except for issues below works, except for issues below
none n
normal displays quotes on <q> Makes sense, but not the spec.
url() nothing nothing nothing missing image icon missing image icon missing image alt
string
open-quote

close-quote

Does not nest quotes correctly, but does include quotes.
no-open-quote

no-close-quote

attr(x)
counter

Listing 3: browser support for the various values of the content property.

 

CSS Background-Color Property

In this tutorial we will be looking at the background-color property, and how to apply it to elements in your web site. The ability to add colors to elements in your page by adding them to a style sheet enables you to create colorful designs while maintaining a consistent look and feel throughout the pages of a web site. We’ll review all the value types of the background-color property introduced in the past 3 sections. We’ll discuss including the background-color property within a style sheet, and problems that may arise depending on the browser.

background-color

The background-color property sets the background color of an element. When you don’t declare a background color, the default value is transparent. This attribute, like all other background attributes, is NOT inherited. All browsers support background colors.

selector { background-color: value;}

Listing 1: CSS syntax for background-color

You can add background color to any element within the body, the body, and the html element itself. Simply declare your color value as in the snippet of code above, where the selector is any CSS selector, such as class, id, tag name, or combination thereof. Use the property name "background-color", and one of the acceptable values described next.

background-color values

The background property can take many types of values:

  • Transparent
  • Color Name
  • RGB Value
  • Hexadecimal Value

Transparent

The default value for background color is "transparent". Since this is the default value and background-color in NOT inherited, you don’t have to declare it on any elements EXCEPT if you’ve declared that all elements of a type have some other background color, and in this particular case you don’t want that element to have that declared background color. For example:

p {background-color: #ff0000;}
p.nocolor {background-color: transparent;}

Listing 2: transparent is the default value, and should only be used with specificity to overwrite a more general declaration.

In this example, all paragraphs will have a background color of red, except paragraphs that have a class of "nocolor", which will not have a background color applied.

IE6 chokes on background-color: transparent when the transparency is applied to an element that is dynamically shown, such as on a drop down menu that is display: none, but is display: block when parent is hovered.

Color Name

There are the 16 colors defined in the W3C specifications. These include: olive, black, gray, silver, white, purple, fuchsia, aqua, navy, blue, teal, green, lime, yellow, red, and maroon. In section 24, Understanding Color Names, we discussed the 140+ color names that are supported by modern browsers, but, other than the 16 listed here, aren’t in the specifications. Feel free to use any of those color names EXCEPT "lightgray", which IE6 sometimes chokes on.

p {background-color: red;}

Listing 3: CSS syntax for background-color using color name

RGB (RGBA) Values

Colors are displayed by combining RED, GREEN, and BLUE light. In CSS, the levels can be defined by percentages or integers between 0 – 255. White can be written as rgb(255, 255, 255) or rgb(100%, 100%, 100%). Black can be written as rgb(0, 0, 0) or rgb(0%, 0%, 0%).

In browsers that support CSS3 (in other words, browsers other than IE), you can set the opacity or transparency level of the background color using background-color: rgba(255, 255, 255, 1);, where 255 is an integer between 0 and 255 or a percent value, and the 1 is any value between 0 and 1, with 0 being completely transparent and 1 being completely opaque.

Note: IE6 and IE7 get "partially compliant" for RGB, since they erroneously display color if integers and percents are mixed. This may be a good thing, but it’s not in the specifications.

Do not using mixed values in RGB, and do not use RGBA without browser targeting: both will fail in non-supporting browsers.

p {background-color: rgb(100%, 0%, 0%);}
p {background-color: rgb(255, 0, 0);}
p {background-color: rgba(255, 0, 0, 1);}

Listing 4: CSS syntax for background-color using RGB and RGBA. The three declarations above have the same value.

Hexadecimal Values

HEX values were discussed in Part 23: Understanding Hex Values. Hex values are the most common, best supported, and recommended way of including colors, including background colors, in CSS. To review, Hex color values are three double digit hexadecimal (hex) notations for the combination of Red, Green, and Blue color values (RGB) preceded by the hash (#) sign. Hex colors can also be written as three single digits.

Property Values for background-color

background-color: transparent;
background-color: rgb(255, 255, 255); 
background-color: rgb(r%, g%, b%); 
background-color: rgba(255, 255, 255, 1); 
background-color: rgba(r%, g%, b%, 1);  
background-color: #fff; 
background-color: #123456;
background-color: white;

Listing 5: Various ways of writing background-color property values.

Browser support for background-color

  Internet
Explorer 6
Internet
Explorer 7
Internet
Explorer 8
Firefox 2 FireFox 3 Safari 3 & 4 Opera 9.64
transparent Issues when dynamic
rgb(r, g, b) renders if value types are mixed renders if value types are mixed
#fff
#ffffff
rgba(r, g, b, a) ignores the entire call ignores the entire call ignores the entire call ignores the entire call ignores the entire call
Color Names OK, except for "lightgray"

Listing 6: Browser support for the various types of background-color property values.

For advanced users: DOM

For those trying to target the element using the Document Object Model, you can use:

document.getElementById("myID").style.backgroundColor

Listing 7: setting or extracting the background-color value using the DOM

3-Column Layouts

Creating a three column layout with CSS: Part 1

Lets start with the XHTML. We start with a parent container, then include a header, content area and a footer, then add three columns to the content area. I will put "ipsum lorem" text in the examples that are linked from this page, but for the tutorial I will keep the content of our three columns, header and footer short.

<div id="parent">
     
  <div id="header">
		<p>HEADER</p>
  </div>
  
  <div id="contentarea"> 
    <div id="colA">
      <p>COLUMN A</p>
    </div>
    <div id="colB">  
      <p>COLUMN B</p>
    </div>
    <div id="colC">
      <p>COLUMN C</p>
    </div>
  </div>
  
  <div id="footer">
    <p>FOOTER</p>
  </div>
  
</div>

Just so we can see what is going on, let’s give them all borders and background colors, so we can tell the difference when we are doing this example. None of the following is part of what I want to teach you, but rather it makes the steps more legible and examples easier to understand.

#parent {
  border: 4px solid #ff0000;
  background-color: #222222;
}
#header  {
  border: 4px solid #ff9900;
  background-color: #444444;
  color #ffffff;
}
#contentarea {
  border: 4px solid #ffff00;
  background-color: #666666;
}  

#colA {
  border: 4px solid #66cc00;
  background-color: #888888;
}
#colB {
  border: 4px solid #3366ff;
  background-color: #aaaaaa;
}
#colC {
  border: 4px solid #663399;
  background-color: #cccccc;
}
#footer {
  border: 4px solid #ff33cc;
  background-color: #eeeeee;
}

<div>s are block level elements, so all this does is create blocks that go across the entire width of the page in normal flow. See our first example. Note: Adding borders to divs, as done above, affects their widths.

Introduction to creating columns

Normal flow is the way a document displays when there is no positioning or floating applied to it. The content will flow down the page, starting with the first element in your document and finishing with the last element in your document. The normal flow for a <div> is to take up the entire width of the page.

Instead of having the blocks of text one under the other, we want them to be next to each other, in "column" format. To create columns 2 things need to happen:

1) The sum of the widths of the three content divs, including the left and right borders, padding and margins of all three blocks of text, has to be less than the width of the container. We achieve this by setting the widths of the columns.

2) The blocks of text need can not appear in the normal flow, with divs above and below each other. Instead, then need to be "floated" next to each other.

Let’s add some CSS just as a preliminary example:

#colA, #colB, #colC {
  width: 30%;
  float: left;
}

I’ve set the width of the three columns to 30% instead of 33% because we have wide borders on the divs (remember: adding borders to divs as affects their widths). So the width is actually 30% + 4px left border + 4px right border. If you shrink the container width to below 240px, the right column will actually drop because the three columns width plus their borders is larger than the container because (30% * 240px + 8px total border) * 3 columns = 240px.

If you take a look at our second example, you’ll note that we have 3 columns, but the page is completely broken! Why? Because of float rules.

Floats: a primer

A float is a element that is laid out according to the normal flow, then taken out of the flow and shifted to the left (if floated left) or right (if floated right) as far as possible. When you float an inline element it becomes a block. Content can flow down the right side of a left-floated element and down the left side of a right-floated element, unless prohibited from doing so by the "clear" property, or because the width of a float is 100%. Floated elements will move to the left or right until their outer edge touches the containing block edge or the outer edge of another float. The top of a floated element will be at the same level as the float next to it, if there is enough room, or at the bottom of the preceding block if the element was originally inline. If there isn’t enough room on the current line for the floated box, it will move down, line by line, until a line has room for the float. (If two floats don’t appear to start on the same line, it is usually because the padding is different.)

Because a floated element is no longer in the normal flow of the document, non-positioned block boxes created before and after the float box flow vertically as if the float didn’t exist. If a parent or containing element only contains floats, the parent element will have no height, as if it were empty. This is what happened in our second example. Note that the #contentarea div (the yellow area) is only 8px high: the height of the top and bottom border.

A float can overlap other boxes in the normal flow. In our example, the three columns are taller than their parent and are overlapping the footer div.

One of the most important things to know about a float, and something that very few people know (and that I ask all potential job applicants) is that a floated element is at least as tall as the tallest floated element contained within it. So, let’s float the parent! but we need to give it a width, or it will shrink to be as narrow as possible. We need to get rid of the border, or our 100% will be 100% + 4px right border + 4px left border, which is more than 100%. Let’s make the background color different too, so it’s more visible. See the third example.

#contentarea { 
  float: left;
  width: 100%;
  border-width: 0;
  background-color: #ffff00;
}

There is a slight problem, which in the 100% width case wouldn’t really matter if we weren’t using such bright colors: note the top border of the footer is not showing. Why? Because the #contentarea has now been taken out of the normal flow. The text of the footer is appearing below the #contentarea because the content area width is 100%, so nothing can fit to the right of it, and therefore must be placed on the next line. Our page looks very different if we give the #contentarea a width of 50%: see the fourth example. The fourth example has similar issues to our second example, where the divs are going beyond the page.

Many instructors will advise to add a <br style="clear: both" /> equivalent here. I say we can do it much better! In the spirit of separating content from presentation, we can fix it via CSS without touching the HTML. Simply add the clear to the next element: the footer.

#footer { 
  clear: both;
}

Now, if you look at the fifth example, the footer falls completely below the content area, and we didn’t have to touch the HTML to add a <br>.

Now you know the basics of floats and the basics of using them to make a multiple column layout. In the rest of the series, I will show you how to make all three columns appear to have the same height, show you how to create columns differing widths, and point out some browser differences: how to avoid IE6 bugs and how to make various browsers render identically.

What we created was fairly ugly, but it worked. I will start from where we left off, but will remove the borders. I will continue to put "ipsum lorem" text in the examples that are linked from this page, but for the tutorial I will keep the content of our three columns, header and footer short. Notice the XHTML has NOT changed:

<div id="parent">
     
  <div id="header">
		<p>HEADER</p>
  </div>
  
  <div id="contentarea"> 
    <div id="colA">
      <p>COLUMN A</p>
    </div>
    <div id="colB">  
      <p>COLUMN B</p>
    </div>
    <div id="colC">
      <p>COLUMN C</p>
    </div>
  </div>
  
  <div id="footer">
    <p>FOOTER</p>
  </div>
  
</div>

We added colors to the divs so we could differentiate the columns from the footer from the header. I have changed the color of the #parent and #contentarea to make them more apparent for this tutorial:

#parent 
  background-color: #ff0000;
}
#header  {
  background-color: #444444;
}
#contentarea {
  background-color: #ffff00;
}  

#colA 
  background-color: #888888;
}
#colB {
  background-color: #aaaaaa;
}
#colC {
  background-color: #cccccc;
}
#footer {
  background-color: #eeeeee;
}

and finally, we added a few lines of CSS to make the columns work:

#colA, #colB, #colC {
  width: 30%;
  float: left;
}

#contentarea { 
  float: left;
  width: 100%;
}
#footer { 
  clear: both;
}

Recap of Part 1

What this bit of CSS did is gave the three columns widths that totaled less than the with of the parent element (the contentarea), floated the three "col" divs so they would appear as columns, and then floated the parent of the three columns so that the container of the columns would be at least as tall as the columns. Remember, because a floated element is no longer in the normal flow of the document, if a parent or containing element only contains floats, the parent element will have no height, as if it were empty. However, a floated element will always be at least as tall as it’s tallest floated child. So, by floating the #contentarea, the content area encompasses the three columns.

What we’re going to focus on in this tutorial:

Let’s take a look at the obvious issues in what we created. If you look at the current rendition of the columns, you will note the following:

  • The parent element (red) is showing thru above the content area, below the header.
  • The columns are all smushed to the left
  • The columns have no padding or margins
  • There is a lot of empty (yellow) space to the right, and jagged edges on the bottom.
  • The content, header, and footer are too tight: they also have no padding.

Making the page look nice

The first issue really has nothing to do with "column layout". It has to do with the default CSS of various browsers. Most browsers by default give margins to paragraph elements. If you are seeing the red #parent between the gray #header area and the yellow #contentarea, it is because the header paragraph has a bottom margin. That is why it is recommended to control your browser CSS defaults with a reset. Let’s control the header and footer and make them look header look nice.

#header {
	   padding: 20px;
}
#header p {
    font-style: italic;
    color: #ffffff;
    margin: 0;

}

#footer {
	   padding: 20px;
}
#footer p {
    text-align: center;
    margin: 0;

}

If you take a look at the page as it stands now, you’ll see it already looks better. So simple! Now lets address the columns.

Making the Columns look nice

What makes nice looking columns? Padding on all 4 sides. Padding between the columns. A middle columns being larger than the side columns. No ugly yellow. Columns being of equal height. hmmmm…. yup, we can do this.

To add padding to all 4 sides, we should simply be able to give padding to the parent container, but that won’t work! We declared the parent to be 100%; so adding padding would make to container wider than the header and footer. To make life easier for right now, let’s declare all widths in pixels instead of percentages.

#parent {
		width: 800px;
     margin: auto;
}
#contentarea {
		width: 760px;
		padding: 20px;
}

We declare an exact width for the parent of 800px. By declaring a margin of auto, the #parent will be centered.

We have added 20px of padding to the content area. That means 20px are added to the left and right (in addition to the top and bottom), so we have a total of 40px of padding between the left and right. 40px padding + 760px width = 800px.

We know we have 760px total for the three columns combined, so lets define their widths:

#colA {
	   width: 170px;
    margin-right: 40px;

}
#colB {

    width: 340px;
    margin-right: 40px;
}
#colC {
		width: 170px
}

If we do the math: 170px + 40px + 340px + 40px + 170px = 760px.
Note that we don’t need to add margin to the right of #col3, since we have the padding on the shell. Also, we use margin right instead of margin left because IE6 has a double-margin-float issue: when an item is floated to the left and and item has a margin-left that is greater than 0, IE6 doubles that width. Similarly, if an element is floated to the right, and the element has a margin-right that is greater than 0, IE6 will double that right margin. The page is actually looking really good in spite of the uneven columns, even in IE6. Let’s fix the uneven columns…

Creating Faux Columns using background images

We don’t want to declare a height on the columns since their heights will vary depending on the amount of content in the page. While there is no other way to ensure that the columns are the same height, we can make them appear to look like they are.

To create "faux columns", or appearance of columns with all the same height, we are going to add a background image to the #contentarea div that creates the appearance of columns for us.

#contentarea {
	   background-image: url(background.gif);
    background-repeat: repeat-y;
}

The image is simply a bar that contains a patch of color that is 210px wide on the left and on the right. Why 210px? The left padding is 20px. ColA is 170px wide. And, we want to cover half of the 40px margin between ColA and ColB with our column color: 20px +170px + 20px = 210px.

Background of faux columns

We’ve repeated this image vertically. To make the columns more interesting, I added a black 1px border. See the image above.

We need to remove the ugliness that we created to make this tutorial easier to follow, so we remove the background colors on colA, colB and colC.

#colA {
  background-color: transparent;
}
#colB {
  background-color: transparent;
}
#colC {
  background-color: transparent;
}

You can either overwrite the background color using the term "transparent" as above, or you can simply remove the CSS that we included earlier to create the background colors on those columns. Take a look at our final example. We have a presentable 3-column layout!

Practice on your own

You’ve learned the general techniques of doing a 3 columns layout. The same techniques can be used for 2-column or 4-columns layouts. Just remember that the columns, along with the added margins, need to be equal to or narrower than the parent holding those columns, accounting for any padding on that parent element.

If the total width of your columns is wider than the parent, your latter columns will drop below your first ones. If you have an item within a column that is wider than the column, like an image or too much padding, your column will drop. If a column drops, it is because your padding + margin + width of all your columns or their content was wider that the container, or because you forgot to float your columns.

The example in this tutorial uses specified widths. You are not required to use those exact widths. Try this tutorial using varying widths. Just remember to not exceed the width of the parent element, and, if you change number of columns or column widths, you will need to create a new "faux column" background to match your new layout.

This example also used padding and margins in a specific way to avoid IE6 bugs and common box model browser issues. I recommend using the padding on the parent and the margin on the columns in the opposite direction of the float to avoid any cross browser issues.

The layout we created may be all you need. But, what if they client says "I want the left nav on the right and the right nav on the left!"? Did you can change the order of your columns without touching your HTML? There is no re-ordering of the columns in a three column layout that isn’t possible.

In this tutorial, we look at the CSS required to change the order of your columns in your CSS without touching your HTML. I will continue to put "ipsum lorem" text in the examples that are linked from this page, but for the tutorial I will keep the content of our three columns, header and footer short. Notice the HTML has NOT changed:

<div id="parent">
     
  <div id="header">
		<p>HEADER</p>
  </div>
  
  <div id="contentarea"> 
    <div id="colA">
      <p>COLUMN A</p>
    </div>
    <div id="colB">  
      <p>COLUMN B</p>
    </div>
    <div id="colC">
      <p>COLUMN C</p>
    </div>
  </div>
  
  <div id="footer">
    <p>FOOTER</p>
  </div>
  
</div>

Listing 1: The HTML used in our examples

#parent {
    background-color: #ff0000;
    width: 800px;
    margin: auto;
}
#header  {
    background-color: #444444;
    padding: 20px;
}
#header p {
    font-style: italic;
    color: #ffffff;
    margin:0 ;
}

#contentarea { 
    float: left;
    width: 760px;
    padding: 20px;
    background-image: url(background.gif);
    background-repeat: repeat-y;
}
#colA, #colB, #colC {
    float: left;
}
#colA {
    width: 170px;
    margin-right: 40px;
}
#colB {
    width: 340px;
    margin-right: 40px;
}
#colC {
    width: 170px;
}
#footer {
    background-color: #eeeeee;
    clear: both;
    padding: 20px;
}
#footer p {
    text-align: center;
    margin: 0;
}

Listing 2: The CSS we are starting off with, based on Part 2 of this series in our embedded style sheet.

Recap of Part 1 and Part 2

In part 1, we floated the three "col" divs so they would appear as columns, and then floated the parent of the three columns so that the container of the columns would be at least as tall as the columns. Remember:

Because a floated element is no longer in the normal flow of the document, if a parent or containing element only contains floats, the parent element will have no height, as if it were empty. However, a floated element will always be at least as tall as it’s tallest floated child.

So, by floating the #contentarea, the content area encompasses the three columns. These three columns were all floated to the left. We declared a width on the parent element, added padding, then used simple addition to determine how wide to make each column and how wide to make the right margins on the first two columns.

Warning: Avoid the double float margin bug! When a margin is applied to a floated box on the same side as the direction the box is floated and the floated box is the first one inside its containing box, the margin is doubled in IE6 and lower. In other words, if a element is floated left, and you have a left margin of 20px on that element, that element will appear to have a left margin of 40px in older versions of IE.

In part 2, we used basic math to take our floated columns from part 1 and turn it into a better looking fixed 3-column layout, including margins and padding. To make the columns appear to have the same height we created "faux columns" by adding a background image to the parent of the three columns. We also added a bit of padding to the header and footer to make them look better. But that’s pretty much it…

Changing the left to right and right to left

The best part about separating the 3 layers of content, presentation and behavior, separating XHTML, CSS and JavaScript, is that you can do major layout changes without touching the original code. We are going to change the order of the columns from Column A-B-C to Columns CBA. To do this we float right instead of left. We also have to change the margins from right to left to avoid the IE double float margin bug.

#colA, #colB, #colC {
    float: right;
}
#colA {
    width: 170px;
    margin-left: 40px;
}
#colB {
    width: 340px;
    margin-left: 40px;
}
#colC {
    width: 170px;
}

Listing 4: CSS rules in an embedded style sheet changing column visual order to C-B-A

That’s all there was to it in this example. Had our #colA and #colC not have been of the same widths, we might have to change either their widths or the background image.

Note that we could have floated column C to the left instead, and then we can omit the left margin on column B.

Remember: class names and ids should be based on function rather than styling. If we had named the columns "left column", "middle column" and "right column", this tutorial would be really confusing. CSS may change your layout, but it won’t change your content. When choosing class and id names, think of the purpose of the styling rather than the styling itself. Choose names that make the funtion of the element clear. When creating a new design, you’ll be able to easily identify the purpose of the styling.

Changing it around again…

Just for yucks-and-giggles, let’s move the columns around again – Columns B-C-A.

#colA {
    float: right;
    width: 170px;
    margin-left: 40px;
}
#colB {
    float: left;
    width: 340px;
}
#colC {
    float: right;
    width: 170px;
}

Listing 5: CSS rules in an embedded style sheet changing column visual order to B-C-A

We floated Column A to the right. Because it’s floated right and we will be floating another element in that direction, we gave it a left margin. We wanted Column B to be on the left, so we float it left. Because no other elements are going to be floated left, there is no need to add a right margin. Then we floated column C to the right. We could have floated column C to the left, and it would have still been in the middle. Had we done so, however, we would have had to put a left margin on column B, and we could have omitted the left margin on column A.

Are there any issues with the redesign? Yes. Column B is the widest, but is now on the left. The background image was created for the middle being the widest. We can either change the widths or change the background. You’ll want to change the background image! You don’t want a wide navigation column and a narrow content columns.

Background of faux columns

Listing 6: Background image with largest column on left

 #contentarea { 
    background-image: url(background2.gif);
}

Listing 7: CSS rule to change the background image (you can also overwrite your image name instead)

You’ll want to create a background image that has the largest column first. You can overwrite your original background image file name. But, since this is a tutorial, I have given the image a new name, and therefore had to update the CSS. Now it looks right.

What have we learned?

By touching only the CSS, and not touching the (X)HTML, we were able to completely change the layout order. Pretty cool. Just remember, in creating 3-column (or more or less), calculate your margins, paddings and widths. If you go over the width of the container, your last column will drop. If you include elements in a column that are wider than the column, unless you declare the overflow property, will increase the width of the column and may cause the column to drop. And, again, if your margins look off in IE6 (or lower), it could be the double margin bug.

Only include margins when necessary. If you omit the margin when not necessary, you get a little bit of leeway should you have an element that increases the size of one of your columns.

Will floating alone take care of everything? No!

What are we missing?

With 3 columns, there are six possible column orders. We can get 4 of the layouts with simple floating and positive margins, but when the first column in content order needs to be in the middle, we have to go into new territory.

A B C – A – float: left; B – float: left; C – float either way
A C B – A – float: left; B – float: right; C – float either way
B C A – A – float: right; B – float: left; C – float either way
C B A – A – float: right; B – float: right; C – float either way

However, there are no combinations that allow us to create the following layouts using our simple CSS.
B A C
C A B

For these combinations, because of the first column in the (X)HTML being in the middle, it would seem that you couldn’t simply float the columns. You actually can. The trick is negative margins:

#colA {
    float:left;
    margin-left:380px;
    width:170px;

}
#colB {
    float:left;
    margin-left:-550px;
    width:340px;
}
#colC { 
    float:right;
    width:170px;
}
 

Listing 8: CSS rules in an embedded style sheet changing column visual order to B-A-C

With negative margins, we are able to place the first column in the middle. We float the first column to the left, but we give it a left margin to enable us to put Column B on the left. Column B is 340px wide. We also want to ensure that we include the 40px margin between Column B and Column A: 340px + 40px = 380px.

This is where the double float margin bug comes into play. Because we are floating left and providing a margin left on the first floated element within a floated parent, IE6 doubles the left margin provided. So we need to include IE6 (and older) conditional CSS in which we halve the left margin:

#colA {
    margin-left: 190px;

}

Listing 9: CSS rules for IE6 and less for changing column visual order to B-A-C

We then want to push Column B all the way to the left (well, inside the parent’s padding). If we simply floated it with no margin, the column would land at 550px from the left padding: the width of Column A (170px) and the left margin on Column A (340px): 170px + 340px = 550px. To put the column in the correct location, we give Column B a negative margin: margin-left: -550px;. The CSS looks weird. It is. But, mathematically, it works.

Note that again with Column C, you can float either left or right, but if you float left you need to include a left margin of 40px, so floating right is simpler.

Practice on your own

You’ve learned the general techniques of rearranging columns in a 3 column layout. I purposely omitted 2 columns combinations. On your own, try creating the following:

  1. A C B
  2. C A B

CSS Reset

Resetting browser default CSS

Whenever I start a new site and begin a new CSS file or CSS file set for the site, my first step is to include CSS to reset the browser CSS defaults.

Different browsers have slightly different default rendering. The default values for margin, padding and line-height differ between browsers. Removing the inconsistent default styling for elements in various browsers creates an equal starting point and allows you to explicitly set your own default settings that are equal in (almost) all browsers. By starting with an equal playing (or presentation) field, your CSS will not only look similar in all browsers, but your CSS file size will be smaller, and the number of aspirin you need to take to complete your site will be reduced.

Code

Here is the code I generally use. I’ll explain it below:

/* CSS BROWSER RESET */

body, div, h1, h2, h3, h4, h5, h6, p, dl, dt, dd, ul, ol, li, 
pre, form, fieldset, legend, input, textarea, label,
blockquote, table, th, td {
		margin: 0;
		padding: 0;
		background-repeat: no-repeat; 
		font-family: Verdana, Arial, Helvetica, sans-serif; 
		font-size: 100%; 
		line-height: 1.4; 
		color: #333333; 
	}
a, span {
		background-repeat: no-repeat; 
		outline: none;	
}

table {
		border-collapse: collapse;
		border-spacing: 0;
	}

fieldset, img, abbr, acronym {
		border: none;
		text-decoration: none; 
	}

ol, ul {
		list-style: none;
	}
caption, th {
		text-align: left;
		font-weight: normal;
	}

q:before, q:after {
		content: '';
	}

input, textarea, select {
		font-family: inherit;
		font-size:inherit;
		font-weight:inherit;
	}


 /* declare your site defaults here */

In your conditionally commented CSS file for IE7 and less include the following:

input, textarea, select {
		font-size:99%;
	}

CSS explained

While you may not use all the elements listed, and you may want your defaults to be slightly different, the above CSS is a good starting point. You might as well include all these elements, because you never know if someone else coding the site, or a future developer, may use those elements.

The first call sets the margin and padding of all elements to none. You won’t have to declare margin and padding of 0 again in your CSS. I have seen style sheets with ‘margin: 0’ included over 100 times. By including this default CSS, you only have to declare margins when you are overwriting the new zero default. Also, you don’t have to remember to explicitly set the body padding and margins.

Different browsers also display h1-h6 differently. This CSS nullifies the browser default settings and makes them look like the rest of your code. This way you decide how you want to display your headings. Also, by declaring a font-size in percentages, we resolve the IE ems rendering issues.

There are some settings in the code above that are redundant or irrelevant and will have no impact, such as setting margins on inline elements. CSS does not penalize you for including properties that are not used. I include all the elements in the first line, even though some of the properties are not used on some of the elements.

The default value for background images is to have them repeat on both the X and Y axis. Generally, you don’t want background images to repeat. The CSS above sets the background-repeat to no-repeat.

Just remember to AVOID use the background shortcut. If you omit one of the elements of the shorthand (background-color,
background-image,
background-repeat,
background-attachment,
background-position) you may inadvertently reset one of the properties to the default.

The call includes several optional/changeable items. Feel free to reset the font-family, color and line-height to your own preferences.

With font-family, include default fonts in the initial CSS browser reset. By declaring the fonts in this way, you will save a lot of characters by not having to declare default fonts elsewhere in your CSS. For example, if you declare your <h1> on your contacts page to have a unique font, you simply have to write something similar to:

#contact h1 { font-family: Hacknslash;} 

If the user doesn’t have the "Hacknslash" font, then it will default to Verdana, Arial, Helvetica, sans-serif, since you declared that in your brower reset CSS.

I chose the grey of #333333 instead of #000000, because black on white can be hard on the eyes. This dark grey is less harsh. You can use whatever color your design requires.

Line height is also up to you. You’ll note that there is no measurement type such as em, px, pt or % included. You can use these measurements. Omitting the measurement sets a number that will be multiplied with the current font-size to set the distance between the lines, similar to declaring em or %.

Since links, spans, code and other in-line elements have no default margin and padding and inherit, I declare them seperately to not overburden the browser rendering engine. I’ve declared two elements in this case as I use a lot of background images in my links and spans and want to ensure that those background images don’t repeat. The outline: none; on the links removes the box you may see around links when the mouse is down.

Note that you should not use the global selector, *, because the browser may overwrite default styling that you want to keep, such as padding on buttons. Also, when the global selector is used, the browser than has to apply the style to every element, which is a heavy load for the browser.

Defaults bullets are removed from ordered and unordered lists. Bullets are placed in different locations in different browsers: Firefox vertically aligns the bullet to text bottom and Internet Explorer vertically aligns the bullet to text top. I like to not only control my bullets, but generally my <li>s are inline, have background images instead of bullets, or are otherwise styled.

The caption and table header declarations are included since browsers tend to center them, and tend to bold table headers. The quote declaration is included since Firefox, Opera and other compliant browsers add quotes to <q>, while Internet Explorer, up to IE7, doesn’t even understand the :before and :after pseudo-classes. (This is resolved in IE8).

Most of the rest of the CSS is self explanatory except perhaps the IE conditional comments portion. Browsers are notorious for rendering forms differently: the input, textarea, select font-size declaration tells IE7 and earlier to not enlarge fonts that are in form elements.

Remember to include your form elements in block level elements. For example, put <textarea> in a <p> element so that it inherits font-family correctly in Opera.

The last line, "declare your site defaults here", is a good spot to declare the other default fonts and colors for your site. If all your h1s are going to be a different color and font, then start with your general, non-classed declarations. Remember to include this Browser Reset CSS at the top of your CSS. In this way, you can use the cascade to declare your defaults without requiring classes. Otherwise, you would have to include additional specificity for things that really should be generally declared.

Other browser reset arguments

There is an argument to remove ALL the defaults, such as bolding of the <strong> element, italicizing of the <em> element, monospacing of the <code> element, etc. The argument is that you should start from scratch, and build up all your own CSS. Below are some additional statements you can consider including in your CSS browser reset:

address, caption, cite, code, dfn, em, strong, th, var { 
	    font-style:normal; 
	    font-weight:normal; 
	} 
	h1, h2, h3, h4, h5, h6 { 
	    font-weight:normal; 
	} 

sup {
		vertical-align: text-top;
	}

sub {
		vertical-align: text-bottom;
	}