• home
  • forum
  • my
  • kt
  • download
  • Working with Color and Images Using CSS

    Author: 2007-07-19 10:27:38 From:

    Color options in CSS are more numerous than what was available to us in HTML. In CSS, you can choose among hexadecimal color, hexadecimal shorthand color, RGB color, color percentages, and the 17 color names supported by CSS 2.1.
    Image options are numerous in CSS. You can control the way images tile (or don't tile), fix them to a location within an element's background, scroll the image or fix the image so text scrolls over itlots of choices. You'll get to try out all these techniques and really get a feel for how CSS not only enables you to use images in ways never available in HTML, but does so with a range of control you'll really appreciate.

    Color is one area where CSS has long been our friend. Because color is determined by a combination of the computer's hardware capabilities, the operating system, and the browser, we've been able to use CSS to color backgrounds and text since relatively early in the life of style sheets. Here you'll learn to apply color to page backgrounds and element backgrounds, and even spice up tables with color.

    Color options in CSS are more numerous than what was available to us in HTML. In CSS, you can choose among hexadecimal color, hexadecimal shorthand color, RGB color, color percentages, and the 17 color names supported by CSS 2.1.

    CSS provides terrific control for images, too. In fact, the capability to place images into the background of any element is helping today's web designers create beautiful designs free of the constraints of tables. In this tutorial, you'll learn how to apply images to backgrounds and elements, and you'll learn about methods of using images for a range of visual techniques.

    Image options are numerous in CSS. You can control the way images tile (or don't tile), fix them to a location within an element's background, scroll the image or fix the image so text scrolls over itlots of choices. You'll get to try out all these techniques and really get a feel for how CSS not only enables you to use images in ways never available in HTML, but does so with a range of control you'll really appreciate.

    So far, you've been focusing on structuring your content with HTML, adding images and media, and working with tables, frames, and forms. Everything you've done so far has been about creating the canvas. Now you'll get a chance to splash some color and life onto that canvas, making your seemingly bland documents come to life.

    NOTE

    The figure examples of color in this book have been limited to grayscale. However, you should feel free to try using any of the rules I describe with any range of colors to get the results best suited to your needs.

    To use color well in CSS, you'll want to know about the various ways color can be defined. Although color can be applied using any number of properties, there are specific value options that you'll want to know about.

    Hexadecimal Color

    Hexadecimal (hex) is a base 16 number system, useful in computing because 8 bits (1 byte of memory) can be represented by a single number or letter. The system uses numbers from 0 to 9 and letters from a to f in any combination of six (and starting with an octothorpe) to represent the correlating red, green, and blue colors (#RRGGBB).

    #FFFFFF = 255, 255, 255 = white
    


    Any hexadecimal combination is allowed in HTML and CSS to represent color (see Example 8-1).

    Example 8-1. Hexadecimal color in style
    body {color: #FFCC99; background-color: #808080;}
    a {color: #66CC33;}
    


    If you applied these styles to a document, the background color would be gray, the text color peach, and the link color bright green.

    Hexadecimal Shorthand

    Hex shorthand enables you to shorten any hex color that has value pairs. This means that each RR, GG, and BB values have to be the same, such as #00CC33 or #888888. In hex shorthand, you take one digit from each value pair, so the results would be #0C3 and #888. In a case as in #808080, the values are not paired, so you can't make it into shorthand (see Example 8-2).

    Example 8-2. Hexadecimal shorthand color
    body {color: #FC9; background-color: #808080;}
    a {color: #6C3;}
    


    NOTE

    You can use hex shorthand in any CSS document, but not in presentational HTML.


    RGB Values

    Another means of representing color in CSS is using the actual RGB values. These can be found in an imaging program such as Photoshop (see Figure 8-1).

    Figure 8-1. Finding the RGB values of a gray color using Photoshop.


    In this case, the color would be presented using the following syntax:

    color: rgb(128, 128, 128);
    


    RGB Percentages

    You can also use percentages of red, green, and blue. A 0% value is black, and a 100% value is white. So, if you set a color as follows:

    color: rgb(50%, 100%, 30%);
    


    the color applied will be a bright green.

    Color Names

    You can use 17 color names to describe color. The colors are aqua, black, blue, fuchsia, gray, green, lime, maroon, navy, olive, purple, red, silver, teal, white, yellow, and orange (orange was just introduced in CSS 2.1):

    color: orange;
    


    You're probably wondering which color value type you should use. The honest answer? All of them! You'll probably find yourself using combinations of keywords, shorthand hex, and hexadecimal most frequently.

    NOTE

    In the upcoming CSS 3.0, many additional colors have been added, but they aren't available for widespread, valid use at the time of this writing.


    Adding color to backgrounds is extremely easy and very useful. You can add color to your page background and any element background.

    Color and the Document Background

    Color is added to the document background by selecting the body element and using the background-color property and a color property value:

    body {background-color: #999;}
    


    Here you see I've chosen a background of dark gray to the entire body. When viewed in a browser, this turns the background color completely gray (see Figure 8-2).

    Figure 8-2. Applying color to a document background.


    NOTE

    You should always set a page background color, even if you intend to use graphics and other element backgrounds in your design. This is because colors are interpreted by browsers very quickly and render before any graphics, providing a more streamlined visual experience for your visitors.


    Color and Element Backgrounds

    With CSS, you can add color to individual element backgrounds. To do this, simply select the element and create a rule. I'll do this for the H1 as I build a style sheet for our simple document:

    body {background-color: #999;}
    h1 {background-color: #ccc;}
    


    Figure 8-3 shows the H1 element with the background color added.

    Figure 8-3. Adding color to the h1 element background.


    I'll go ahead and add rules for the paragraph and anchor element color, too (see Example 8-3).

    Example 8-3. Document and background elements with color added
    body {background-color: #999;}
    h1 {background-color: #ccc;}
    p {background-color: #fff;}
    a {background-color: #ccc;}
    


    Figure 8-4 shows how the background color is applied.

    Figure 8-4. Background colors as applied to the document and element backgrounds; note that the element background colors stretch to the full width of the element.

    In this section, I'll show you how to add a little spice to your tables using background colors. So far, you've used element selectors, which relate directly to a specific HTML element, such as body, H1, p, and a. In this section, you'll add what's known as a class selector.

    Class selectors are custom selectors that you give a name to; you precede that name with a dot, as in .classname. Classes are then applied to an element in the HTML using the class attribute, with a value of the class name:

    <tr class="classname"> . . . </tr>
    


    Typically, you'll want to describe the function of the class rather than the presentation. So, if you're going to apply a background color to every other table row, you'll want to name your class something like .alternaterow instead of .gray. This way, if you want to change the color, you needn't change the class name throughout your documents, which defeats the management advantages of CSS.

    Example 8.4 shows a modified table you first worked with in tutorial 4, "Creating Tables." You'll note that I made one change in the table markup: I took out all the table attributes except for cellspacing. This is because there is no effective means of providing cellspacing in CSS.

    I've also added an embedded style sheet that includes the table width, border, and padding styles, along with element selectors and a class selector to style the table using background colors in the elements.

    Example 8-4. Styling the table with element and class selectors
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
              "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <title>working with style</title>
    
    <style type="text/css">
    body {color: white;}
    caption {background-color: #999; border: 1px solid black;}
    table {background-color: #ccc; border: 1px solid black; padding: 5px; width: 90%;}
    th {background-color: #333; border:}
    tr {background-color: #999;}
    td {background-color: #ccc; border: 1px solid black;}
    .highlight {background-color: #fff; color: orange;}
    </style>
    
    </head>
    
    <body>
    
    <table cellspacing="5">
    <caption>Comparing weather and time zones</caption>
    <tr>
    <th>Location</th>
    <th>Tucson, Arizona</th>
    <th>Las Vegas, Nevada</th>
    </tr>
    <tr>
    <th>Weather</th>
    <td>Warm to Hot</td>
    <td>Warm to Hot</td>
    </tr>
    <tr>
    <th>Time Zone</th>
    <td>No Daylight Savings</td>
    <td  class="highlight">Mountain Standard Time</td>
    </tr>
    </table>
    
    </body>
    </html>
    


    Figure 8-5 shows the results.

    Figure 8-5. Styling a table with element and class selectors.


    NOTE

    You'll also notice I added borders to spice things up a bit. You can learn more about styling borders in tutorial 11, "Margins, Borders, and Padding."


    As you are beginning to find out, you can do a lot with CSS to enhance your documents. Here we've turned a plain-vanilla table into something with a little style.

    You can attach a background graphic to the document or any element, just as you can with background color. There are more ways to control backgrounds with CSS, though, giving you a broad range of options when it comes to applying visual design to your site. By combining a page background with element backgrounds, you can create layers of images and numerous special effects.

    Background graphics are typically either small tiles used to repeat to create a wallpaper pattern, or horizontal or vertical graphics with sections of color, imagery, and even typographic features. You can find many predesigned backgrounds online (see Figure 8-6), or you can create your own.

    Figure 8-6. A background texture for a wallpaper effect I found at http://www.grsites.com/textures/.


    First, let's have a go at attaching the background graphic to the document. This is done by selecting the body and creating a rule using the background-image property with a value of the image's location and name:

    body {background-image: url(gray.jpg);}
    


    Figure 8-7 shows the results of the tiled background within a web browser. You'll notice how the image tiles into the entire viewable area, creating an intriguing look.

    Figure 8-7. Tiling a background in the body.


    NOTE

    Tiling images in a background is normal behavior for the browser. With HTML, you have no control over how an image tiles. As you'll soon see, CSS gives you far more control over how background images can be manipulated.


    You can also add images to elements. If you wanted this image to appear in the background of all your headings, you could create the following rule:

    h1, h2, h3, h4, h5, h6 {background-image: url(gray.jpg);}
    


    In this case, all header backgrounds would use the background tile.

    QUANTUM LEAP: GROUPING SELECTORS

    The rule I just wrote with all headers separated by commas is a means of grouping selectors that all take the same rules. This way, I can group any selectors that share rules by naming the selector and following it with a comma:

    h1, p, .footertext {color: teal;}
    

    This way, H1, p, and the class of footertext will all be colored teal. You can continue writing additional rules for unshared styles:

    h1 {font-size: 24px;}
    

    With both of these rules in the same style sheet, both styles would be applied, resulting in the h1 being 24 pixels with a color of teal.


    CSS enables you to control the way backgrounds tile. This is done using the background-repeat property along with the appropriate value.

    Tiling Along the Horizontal Axis

    The horizontal axis, also referred to as the x-axis, enables you to tile a background along the element's horizontal axis, but not the vertical one:

    body {background-image: url(gray.jpg); background-repeat: repeat-x;}
    


    Figure 8-8 shows the results.

    Figure 8-8. Controlling horizontal tiling with the background-repeat property.


    Tiling a Background Along the Vertical Axis

    Similarly, you can repeat a background tile along the vertical axis only. To do this, you use the background-repeat property along with a value of repeat-y:

    body {background-image: url(gray.jpg); background-repeat: repeat-y;}
    


    You can see that the image is now tiled along the vertical axis only in Figure 8-9.

    Figure 8-9. Repeating a background along the vertical axis.


    You can also set the image to not repeat using a value of no-repeat:

    body {background-image: url(gray.jpg); background-repeat: no-repeat;}
    


    This results in the tile showing up in the top-left corner one time, with no repeating.

    QUANTUM LEAP: OTHER AVAILABLE PROPERTIES

    Two other values are available for the background-repeat property. The first is simply repeat. Using it causes the tile to repeat on both the horizontal and vertical axes, which is default behavior for backgrounds; you probably won't use it unless you are specifically overwriting a previous rule. Many CSS properties offer a default value of this nature for precisely that reason.

    The second available value is inherit. This value is available for most all properties, and because most properties are inherited, it simply strengthens the case that the property will be inherited by its descendents. You will likely not use inherit too frequently, either, unless you are specifically undoing another rule or you are applying the value to a property that is not normally inherited but that supports the value, such as background-position.

    Along with tiling, you can position a background graphic into the document or any element you like. To position a background graphic, you have to set the background-repeat value to no-repeat first. Then you can position it using any one of the values described in Table 8-1.

    Table 8-1. Background Position Property Values

    Value Type

    Example

    Placement

    Percentage

    background-position: 0% 0%;

    Top-left corner

     

    background-position: 100% 100%;

    Bottom-right corner

     

    background-position: 14% 80%;

    14% across, 80% down

    Length

    background-position: 20px 20px;

    20px from left, 20px down

    Keywords

    background-position: top left;

     
     

    background-position: left top;

    0% 0%

     

    background-position: top center;

     
     

    background-position: center top;

    50% 0%

     

    background-position: right top;

     
     

    background-position: top right;

    100% 0%

     

    background-position: left;

     
     

    background-position: left center;

     
     

    background-position: center left;

    0% 50%

     

    background-position: center;

     
     

    background-position: center center;

    50% 50%

     

    background-position: right;

     
     

    background-position: right center;

     
     

    background-position: center right;

    100% 50%

     

    background-position: bottom left;

     
     

    background-position: left bottom;

    0% 100%

     

    background-position: bottom;

     
     

    background-position: bottom center;

     
     

    background-position: center bottom;

    50% 100%

     

    background-position: right bottom;

     
     

    background-position: bottom right;

    100% 100%


    Confused yet? So was I, until I started playing around with positioning backgrounds. The important thing to remember is that for percentage and length values, the first value is the horizontal value and the second is the vertical value. With keywords, the behavior is as described in the table.

    NOTE

    You can combine percentages and length values with background-position but not keywords, so you can have a value of 100% 20px but you cannot have a value of 100% left.

    If only one percentage or length value is given, it is applied to the horizontal position, and the vertical position defaults to 50%.


    Example 8-5 sets up the style sheet for a sample of each value type.

    Example 8-5. Positioning a background graphic with percentage, length, and keywords
    [View full width]
    h1 {background-image: url(tile.gif); background-repeat: no-repeat; background-position: 0%
     0%;}
    h2 {background-image: url(tile.gif); background-repeat: no-repeat; background-position:
     100px 4px;}
    h3 {background-image: url(tile.gif); background-repeat: no-repeat; background-position:
     bottom right;}
    


    Note that I've defined not only the image, but also the repeat value of no-repeat, to ensure that the background-positioning values work properly. Figure 8-10 serves up the resulting background graphic positions.

    Figure 8-10. The small gray-lined tile being positioned within the background of header elements.

    You can have your background image fixed to the browser's viewport, or allow it to scroll along with the document by using the background-attachment property along with a value of either fixed or scroll.

    Typically, this is used for either the entire body or content areas within the document. However, as you've seen so far, you can use it in any element where it makes sense to do so.

    Consider the following rule:

    [View full width]
    body {background-image: url(arrows.gif); background-position: right; background-repeat: no-repeat; background-attachment: scroll;}


    Here, I've attached a background image, positioned it to the right with no repeat, and scrolled the background. This actually creates a rule that mimics default browser behavior, which is to scroll the background with the content (see Figure 8-11).

    Figure 8-11. When a background graphic is set to scroll, it scrolls along with the element to which it's attachedin this case, the body.


    Now, if you were to write the same rule with a value of fixed, the results would be quite different (see Figure 8-12).

    Figure 8-12. No matter where I scroll, the background image remains fixed in this case.


    You can achieve a range of interesting effects using scrolling with backgrounds. Of course, you'll want to try it for yourself, to really see how scrolling works in a browser. Try a range of options: Set the image to repeat, for example, or position your image in different locations and try out both the fixed and scroll values to compare how each works.

    NOTE

    Some accessibility advisors suggest that using scrolling text over backgrounds is more difficult to see. I know this much: I get motion sensitivity fairly easily, and if I'm trying to scroll through text over a textured background, it will make me a little woozy. So use this technique with care!

    One thing I didn't introduce while discussing background colors is the value of TRansparent for the background-color property. There's a method to my madness, of course: I wanted to introduce background images so you could get the full value of this very important CSS option.

    Example 8-6 describes the table used earlier, this time with a background image set for the body. You'll also notice that I've changed the .highlight class to have a background-color property value set to transparent.

    Example 8-6. Setting up a transparent background color
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
               "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <title>working with style</title>
    
    <style type="text/css">
    body {background-image: url(gray.jpg); color: white;}
    caption {color: black; border: 1px solid black;}
    table {border: 1px solid black; padding: 5px; width: 90%;}
    th {background-color: #333;}
    tr {background-color: #999;}
    td {background-color: #ccc; border: 1px solid black;}
    .highlight {background-color: transparent; color: orange;}
    </style>
    
    </head>
    
    <body>
    
    <table cellspacing="5">
    <caption>Comparing weather and time zones</caption>
    <tr>
    <th>Location</th>
    <th>Tucson, Arizona</th>
    <th>Las Vegas, Nevada</th>
    </tr>
    <tr>
    <th>Weather</th>
    <td>Warm to Hot</td>
    <td>Warm to Hot</td>
    </tr>
    <tr>
    <th>Time Zone</th>
    <td>No Daylight Savings</td>
    <td  class="highlight">Mountain Standard Time</td>
    </tr>
    </table>
    
    </body>
    </html>
    


    As you can see, this allows the background behind the element to show through (see Figure 8-13).

    Figure 8-13. The transparent value allows the background to show through the elementin this case, the table cell with the highlight class shows.

    Another interesting piece of CSS is that certain properties have a shorthand equivalent. This occurs only with a handful of properties; background is one of them.

    Shorthand properties combine the features of all related properties. In the case of ackground, this means that color, image, repeat, and attachment can all be combined into one rule using the background property.

    To help you compare, Example 8-7 describes the styles for all the background properties.

    Example 8-7. Longhand background styles
    body {
              background-color: white;
              background-image: url(images/lemon-slice.gif);
              background-repeat: no-repeat;
              background-attachment: scroll;
              background-position: right bottom;
    }
    


    The shorthand version equates to this:

    body {background: white url(images/lemon-slice.gif) no-repeat scroll right bottom;}
    


    I created an HTML page with some mock text and applied the background styles using the shorthand version (see Figure 8-14).

    Figure 8-14. Applying background properties using CSS shorthand.


    Of course, either the longhand or the shorthand versions would have worked to achieve the same end.

    QUANTUM LEAP: WHEN TO USE SHORTHAND

    Shorthand CSS is extremely useful when you're trying to conserve file size. It also can make general management of your CSS easier. I tend to use it wherever I can, with few exceptions.

    However, I have heard people (particularly those who work in professional web-development team environments) point out that shorthand is harder for novices to work with. Some team managers choose to author their CSS in longhand no matter what because they find that it can help cut down on errors and confusion when diverse skill levels exist within a team.

    Hopefully, you're having a bit more fun now that you can use color and images to spruce up your pages.

    As you can see, CSS gives you so many more options for color management that it's not funny. Even more flexible is the way in which you can now manipulate images to create your designs via CSS, yet keep them separate from any inline images.

    The CSS Zen Garden (http://www.csszengarden.com/) is a fantastic place to check out how images aren't used anywhere inline. All the fabulous images within that site are placed into element backgrounds and managed with the techniques learned in this tutorial.

    Moving along, you're going to learn how to style your text effectively. I waited until after color and imagery because you can integrate both with your text.

    I can't wait to see what you come up with!


    discuss this topic to forum

    relation tutorial

    No relevant information

    Category

      CSS (142)

    New

    Hot