Chapter 4
Working with Graphics
In This Chapter
Working with the <img>
tag
Displaying foreground images
Displaying background images
Placing graphics on the page
Working with repetitive images
Content comes in a number of forms, but the two most common forms are text and graphics. CSS provides a number of methods for dealing with both of these forms. Earlier chapters of this book focused on text. This chapter begins your foray into graphics.
Most developers rely on premade graphics to create sites. So this chapter focuses on the mechanics of working with graphics — the techniques used to present them onscreen, rather than on any design or aesthetic element of graphics. Of course, the starting point for most graphic elements is the <img>
tag. Even though the <img>
tag isn't strictly a CSS element, knowing about the tag is essential if you want to use CSS to control the presentation of graphics.
An object can contain any number of foreground images and a single background image. (The background can actually consist of multiple images, but these images are combined into a cohesive whole — you see a composite of the various image elements.) The chapter also discusses techniques for positioning graphics onscreen and using repetitive images to create special effects.
The one artistic technique I discuss in this chapter is the transformation because it has a mechanical element to it. Transformations can subtly or radically change the appearance of your image. For the most part, the transformations change the way the image is presented onscreen — the way it’s zoomed, rotated, positioned, or skewed. These are the sorts of transformations that the chapter will focus on — nothing of a completely radical nature.
Understanding the <img> Tag
The <img>
tag has been around for a long time — so long, in fact, that it has picked up a bit of baggage along the way. Developers who think that the <img>
tag supports certain attributes may be surprised to find that it doesn't — at least not anymore — because those attributes have been deprecated (removed) as new HTML versions have appeared on the scene. For example, the align
attribute isn't available in HTML5 — it was deprecated in HTML4 because CSS already provided good transformation alternatives to the align
attribute. Unfortunately, one casualty of deprecation, longdesc
, affects people with special needs, but few sites actually implemented this useful feature anyway. Because you need to know the attributes used with HTML5 in order to work with the examples in this book, the following list provides you with an updated list of attributes that you can use for reference.
alt
: Provides a textual description of the image for those who can't see it. A screen reader will describe the image to the person. It's important to keep the description short and focused. Even though a picture is worth a thousand words, the viewer likely won't have time to hear them all.
crossorigin
: Allows usage of images located on another server as specified within an <img>
tag enclosed in a <canvas>
tag. The browser will act as if the image is served by the local server, rather than the foreign server. Because the image is on another server, the src
attribute is normally modified to include additional server details. To use this feature, you must also provide an origin
HTTP header that describes the location of the server. You can also use JavaScript to access this information (see http://saltybeagle.com/2009/09/cross-origin-resource-sharing-demo/
or https://developer.mozilla.org/en-US/docs/HTML/CORS_Enabled_Image
for an example of performing this task). This attribute can have the following values:
• anonymous
: The foreign server doesn't require any special login to use the image.
• use-credentials
: The foreign server requires a username and password to gain access to the image. The credentials are supplied using a variety of means, including a cookie, x.509 certificate, or HTTP basic authentication.
height
: Specifies the height of an image using any supported unit of measure (see Chapter 1 for details).
ismap
: Specifies that the image is a server-side map when included (there's no value associated with this attribute). Mapped images can be used to perform all sorts of tasks, such as acting as a site map (redirecting viewers to other places on the site).
src
: Defines the source of the image. Normally, this attribute contains a simple URL. When you're working with the crossorigin
attribute, however, src
takes on new meaning (see the crossorigin
attribute entry for details).
usemap
: Specifies that the image is a client-side map. You provide the name of the <map>
tag to use with the image.
width
: Specifies the width of an image using any supported unit of measure (see Chapter 1 for details).
Working with Foreground Images
You may have noticed that there are some interesting attributes missing from the <img>
tag in the previous section. For example, it's no longer possible to define a border around your image using the border
attribute (see http://www.w3schools.com/tags/tag_img.asp
for a discussion of other deprecated attributes). This section of the chapter focuses on the sorts of decoration that you can perform on an image that doesn't include transforming the image in any way (Chapter 5 discusses transforming graphics).
Before you can do anything, you need a basic page to work with. The following procedure gets you started.
1. Create an image file of any sort that you want to see while working on the example. Give this image file a name of CuteCat.JPG.
The downloadable source code includes a sample file containing a 400 × 378 pixel image that you can use. The filename and extension are important because you need a specific name when writing the code.
2. Create a new HTML5 file with your text editor.
Your editor may not support HTML5 files. Any text file will do.
3. Type the following code for the HTML page.
<!DOCTYPE html>
<html>
<head>
<title>Simple Graphics Example</title>
</head>
<body>
<h1>Interact with an Image </h1>
<div id="ImageContainer">
<img alt="A Picture of a Cute Cat."
title="A Picture of a Cute Cat."
name="CuteCat"
id="CuteCat"
src="CuteCat.JPG" />
</div>
</body>
</html>
This example displays a heading and an associated picture. The page looks like the one shown in Figure 4-1 when you use the image supplied with the downloadable source code.
Figure 4-1: Create a page that contains an image that you’ll work with in the sections that follow.
4. Save the file as SimpleGraphics.HTML.
The sample will appear in other chapters, so naming is important.
Now that you have a page to work with, it’s time to try interacting with the image. The following sections discuss some common tasks you perform.
Creating a border
One of the more common changes you can make to an image is to add a border. This sets off the image from the other content on the page. Of course, CSS offers a broad range of border types. The trick is to get the border to display around the image in such a way that you can perform other tasks with that border later. That's where the <div>
in the HTML code comes into play. It provides a container that can hold all sorts of things (such as the <div>
used as a container for the <img>
tag shown in the previous example) — and you can interact with that container in various ways. The following procedure helps you add a border around the image.
1. Create a new CSS file with your text editor.
Your editor may not support CSS files. Any text file will do.
2. Type the following CSS style information.
#ImageContainer
{
border-style: groove;
border-width: thick;
border-color: gray;
padding: 5px;
float: left;
}
The majority of this style information is about the border. Adding padding
to the border makes it stick out more like a frame. The float
value keeps the <div>
around the image, rather than having it follow the right side of the browser, when a user resizes the browser window.
If you want the image on the right side of the page, rather than the left, substitute float: right;
. The entire container, image included, will reside on the right side of the page, rather than the left. As the user changes the browser window, the image will remain the same size, but it will move with the right side of the browser window.
3. Save the file as SimpleGraphics.CSS.
The sample will appear in other chapters, so naming is important.
4. Add the following code to the <head>
area of the HTML file.
<link rel="stylesheet" href="SimpleGraphics.CSS" />
This code creates the link between the HTML file and the CSS file.
5. Save the HTML file and reload the page.
You see the border shown in Figure 4-2.
Figure 4-2: Create a page that contains an image with a border that you’ll work with in the sections that follow.
Centering the image
One of the most commonly asked questions is how to center an image on the page. Unfortunately, most of the answers you receive discuss just the <img>
tag, without showing how to center a container. Using a container is important because you may want to add other items to that image later. The following procedure tells how to center the image.
1. Add the following style to the SimpleGraphics.CSS
file.
#ImageContainer img
{
height: 400px;
width: 400px;
margin: 0px;
}
The purpose of this style is to create an image of a specific size. There are a number of ways to deal with images of various sizes. This is one of them. It works well when most of your images are about the same size.
In some cases, such as when you’re centering images of widely different sizes, you must resort to using JavaScript. In order to place an image in the center of the page, you must know the size of the image. Many third-party libraries make it easy for you to center images onscreen — the CSS-only technique does have limits.
2. Add the following code to the #ImageContainer
style.
position: absolute;
height: 400px;
width: 400px;
left: 50%;
margin-left: -205px;
This code sets the <div>
position as absolute and gives it the same size as the image, so that the <div>
and <img>
tags are linked. It then places the left side of the <div>
50% across the page, so that no matter how the user changes the browser window, the left side of the <div>
will remain center. Of course, you don't want to center the left side of the <div>
— you want to center the image. The margin-left
setting moves the left margin 205 pixels to the left (half the overall size of the image, plus the padding), so that the center of the image is now in the center of the page.
3. Save the CSS file and reload the page.
You see the image and its frame centered on the page as shown in Figure 4-3.
Figure 4-3: The image is now centered on the page.
Adding a caption
You might be wondering what sort of content could go with an <img>
tag. You could add buttons, say, to move from one image to another in a gallery. However, it's more common to add a caption so that people looking at the site have some idea of what the image is all about. The following procedure describes how to add a caption to the image.
1. Add the following tag (in bold) to the <div>
found in the SimpleGraphics.HTML
file and save the file.
<div id="ImageContainer">
<img alt="A Picture of a Cute Cat."
title="A Picture of a Cute Cat."
name="CuteCat"
id="CuteCat"
src="CuteCat.JPG" />
<p>A picture of a cute cat!</p>
</div>
2. Add the following style to the SimpleGraphics.CSS
file.
#ImageContainer p
{
text-align: center;
height: 20px;
width: 400px;
margin: 0px;
}
It’s possible to add any amount of text formatting desired. However, you must provide a text element of a specific size or else the border might appear in a place other than where you’d like it to appear.
3. Modify the #ImageContainer
height
property to accommodate the new text element. The property should look like this:
height: 420px;
Any time you add new features to the container, you must resize the container to hold them. The original container size was 400 pixels. You’ve added 20 pixels worth of text, so the new size is 420px.
4. Save the CSS file and reload the page.
The image now includes a caption as shown in Figure 4-4.
Figure 4-4: Adding a caption makes the intent of the image clearer.
Adding Background Images
Background images add flavor to a site. People may not think users pay much attention to them, but the right background image can have a major impact on your site. Working with background images is a little different from foreground images. For one thing, there’s normally only one background image for any given object on the site and the background image is usually limited to the main object, which is the body of the page.
Using CSS alone
There are a number of ways to create a background for your page using CSS alone. The easiest method is to simply define a background color. Of course, having just a single background color would be boring. However, you see sites that use a simple background color as a palette for adding content — and it does work.
Another technique is to provide a frame for the entire page. You create a border around the <body>
tag. A combination of multiple layers and special effects can create amazing border effects for your page. Using borders with other objects increases the number of things you can do with regard to framing effects.
Working with linear gradients
Most people will want something a little more exciting than a background color or a frame for their sites. For example, you can rely on a linear-gradient()
function to perform the task. Using a linear-gradient()
, you can create lines (horizontal, vertical, and angled), diamonds, and squares. When you combine the linear-gradient()
with other gradient methods (such as the radial-gradient()
) you can create all sorts of patterns (as described later in this section). For now, create a simple linear-gradient()
using the following procedure to get a feel for how they work.
1. Create a new HTML5 file with your text editor.
2. Type the following code for the HTML page.
<!DOCTYPE html>
<html>
<head>
<title>A Non-image Background</title>
<link rel="stylesheet"
href="PatternedBackground.CSS" />
</head>
<body>
<h1>A Simple Heading</h1>
<p>Simple text to go with the heading.</p>
</body>
</html>
The main purpose of this example is to focus on backgrounds, so the content is quite simple. All you see is a simple header and paragraph.
3. Save the file as PatternedBackground.HTML.
The sample will appear in other chapters, so naming is important.
4. Create a new CSS file with your text editor.
5. Type the following CSS style information.
body
{
background: linear-gradient(
45deg, Crimson, Transparent, RoyalBlue);
background-color: #00ff00;
background-size: 100px 100px;
}
The focal point of this pattern is the background
property, which relies on the linear-gradient()
function. You can use this function in a number of ways; the example shows one simple way. It begins by telling the linear-gradient()
function to draw the line at 45 degrees. There are three colors in the gradient: Crimson
, the background color (Transparent
shows the background), and RoyalBlue
. The gradient will begin with Crimson
, transition to the background color, and end with RoyalBlue
, all in equal proportions.
The background-color
property defines a value of green in this case. The background-size
property defines the size of the gradient pattern. It would be easy to obtain a number of different effects using the same linear-gradient()
and varying these last two properties.
6. Save the file as PatternedBackground.CSS.
The sample will appear in other chapters, so naming is important.
7. Save the HTML file and reload the page.
You see the background shown in Figure 4-5, which is actually quite dramatic. The background automatically repeats no matter how the user resizes the window.
Figure 4-5: Using linear-gradients helps you create interesting backgrounds.
Experimenting with linear gradients
You could work for quite some time trying to figure out which color combinations look best and how best to present your gradient to the world. In addition, you can use more than just two or three colors, so gradients can become complex color undertakings. Gradients can also have special settings, such as controlling the amount of each color to use. Fortunately, there's a fast way to discover the settings to use: the CSS3 Gradient Generator (http://gradients.glrzad.com/
) shown in Figure 4-6.
To use the CSS3 Gradient Generator, begin by setting the colors you want to use under Color Swatches. The plus sign (+) next to this heading lets you add more colors. Likewise, the red X button on the slider lets you remove colors, which isn’t very obvious. The Gradient Sample shows a color swatch of the selections you’ve made. The Gradient Direction settings let you create angled and vertical variations of your color swatch. You can also set the kind of color settings to use with the Color Format settings. The result of your manipulations appear in The Code, which you can copy to your editor and use as part of your application.
Figure 4-6: The CSS3 Gradient Generator helps you experiment with gradients.
Obtaining CSS patterns online
Creating simple effects using gradients is easy. However, creating something truly spectacular takes time and artistic ability. Most developers really don't have the time or skills required to create something dazzling using CSS3 alone (or CSS3 combined with graphics) — that's where designers come into play. Many designers allow you to use their designs. You can find a number of sites with simple examples, such as those found at http://lea.verou.me/demos/css3-patterns.html
. As you can see in Figure 4-7, these patterns all rely on the CSS linear-gradient
function.
In order to use these designs, you need to right-click your browser and choose the option for viewing the source code. The designs are all documented in the <style>
tag that appears at the top of the page. All you need to do is copy the desired design from the page source to your application.
Figure 4-7: Many sites will provide you with free CSS3 designs you can use as backgrounds.
The site at http://lea.verou.me/css3patterns
provides a much larger group of significantly more complex designs, as shown at Figure 4-8. These patterns are all labeled so you know what the designers have named them. Click a pattern and you go to a page with that pattern as a background. In addition, the code for that pattern appears in a window with the pattern. You can simply copy it from this window to your application. Believe it or not, all of these gorgeous designs use gradients alone — none of them rely on downloaded art to achieve their goals.
Figure 4-8: A few sites provide you with truly amazing backgrounds you can use for your page.
Using a single image
The simplest, most compatible way to create a background that has at least a little pizzazz is to use a single image. The right image says a lot about your site and provides continuity between pages. Because this approach is so standard, you see it used on a lot of sites. All you really need to know to use it is the background-image
property, as shown in the following procedure.
1. Create a new HTML5 file with your text editor.
2. Type the following code for the HTML page.
<!DOCTYPE html>
<html>
<head>
<title>A Single Image Background</title>
<link rel="stylesheet"
href="SingleImage.CSS" />
</head>
<body>
<h1>The Cute Cat</h1>
<p>A page that has a cute cat as a background.</p>
</body>
</html>
3. Save the file as SingleImage.HTML.
The sample will appear in other locations, so naming is important.
4. Create a new CSS file with your text editor.
5. Type the following CSS style information.
body
{
background-image: url("CuteCat.jpg");
background-color: SaddleBrown;
color: SeaGreen;
font-size: x-large;
text-shadow: 1px 1px Yellow;
}
This is the simplest form of a single background image. The background-image
property has a single url()
function associated with it. Just in case the user can't display the image (or chooses not to), you need to set an appropriate background color. Depending on the image (the example uses one that's particularly hard to work with when it comes to text), you may need to set the text color and size to make the content easy to read.
This is one place where using the text-shadow
property may make the difference between user joy and user complaints. Use contrasting colors for the font and shadow so that the two work together to make the content viewable against an image with a range of colors.
6. Save the file as SingleImage.CSS.
The sample will appear in other locations, so naming is important.
7. Load the SingleImage
page.
You see the background shown in Figure 4-9. Notice that the graphic starts in the upper-left corner and automatically repeats as needed to fill the entire window.
Figure 4-9: Background images can lend just the right level of interest to a page.
Using multiple images
It’s possible to combine multiple images into a single image when working with CSS3-capable browsers. At least one of the images must have transparent regions that allow the second image to peek out from behind it. The following procedure modifies the SingleImage example to contain two images. The second image is supplied with downloadable source as PawPrint.GIF. However, you can easily substitute an image of your liking instead (as long as the image has the required transparent regions).
1. Open the SingleImage.CSS
file.
2. Modify the body
style so that the background-image
property now contains two images, as shown here.
body
{
background-image: url("PawPrint.gif"),
url("CuteCat.jpg");
background-color: SaddleBrown;
color: SeaGreen;
font-size: x-large;
text-shadow: 1px 1px Yellow;
}
Notice that the two image entries are separated by a comma — not many multi-entry properties require commas, but this is one of them. The order in which the images appear is also important. The image containing the transparency must appear first because it appears over the top of the second image. If you reverse the entries, the image lacking transparencies will be on top and you’ll see only one image.
3. Save the CSS file as MulitpleImage.CSS.
4. Open the SingleImage.HTML
file.
5. Modify the <title>
and <link>
tags so they look like this:
<title>A Multiple Image Background</title>
<link rel="stylesheet"
href="MultipleImage.CSS" />
6. Save the HTML file as MultipleImage.HTML.
7. Load the MultipleImage
page.
You see the background shown in Figure 4-10. Notice how the paw prints overlay the original image but don’t conceal it completely.
Figure 4-10: It’s possible to combine multiple images into a single background.
Positioning Graphics
You can find techniques for positioning foreground graphics in the "Centering the image" section of this chapter. In essence, you use the combination of the left
, right
, top
, and bottom
properties to provide basic positioning. Tweaking the position involves using the margin-left
, margin-right
, margin-top
, and margin-bottom
properties. To ensure that the image stays in one place, normally you set the position
property to absolute
. Of course, all positioning is relative to image size, which you set by using the height
and width
properties.
Background images also have positioning functionality. You can also control the background image position, margin, and size. The following procedure provides an example of how you might modify the SingleImage
example to place a single copy of the image in the center of the page (and keep it there no matter how the page is scrolled).
1. Open the SingleImage.CSS
file.
2. Modify the body
style so that the image is fixed in the center, as shown here.
body
{
background-image: url("CuteCat.jpg");
background-color: SaddleBrown;
color: SeaGreen;
font-size: x-large;
text-shadow: 1px 1px Yellow;
background-position: center;
background-attachment: fixed;
}
The background-position
property makes it possible to define the placement of the primary copy of a background image. The default setting places the image in the upper-left corner, which may not be very pleasing to the eye.
The background-attachment
property defines how that image is attached to the browser's background. Setting this value to fixed
means that the image stays in the same location even when the user resizes the display or scrolls the content.
3. Save the CSS file as BackgroundPosition.CSS.
4. Open the SingleImage.HTML
file.
5. Modify the <link>
tag so it looks like this:
<link rel="stylesheet"
href="BackgroundPosition.CSS" />
6. Save the HTML file as BackgroundPosition.HTML.
7. Load the BackgroundPosition
page.
You see the background shown in Figure 4-11. Notice that the initial image is now centered and the copies radiate out from it.
Figure 4-11: Centering a background image often makes the page more pleasing.
Working with Repetitive Images
There are a number of ways you can use repetitive images — or keep from using them. For example, when you work with a background, you automatically get repeating images. If you’d prefer not to see multiple copies of the image, you need to tell the browser to display only one. Likewise, you may encounter situations where you really do want repeating images, but in a specific way, such as creating a border around a graphic. The following sections discuss these two scenarios, but you can use the information you obtain to control image repetition in other ways.
Changing repetitive backgrounds
There are situations where you only want a single copy of a background picture. It may be that the image you’ve used is something that doesn’t repeat well or is large enough that you really don’t want it repeated. The following procedure demonstrates a technique you can use to tell the browser to use just one copy of a background image.
1. Open the BackgroundPosition.CSS
file.
2. Modify the body
style so that the image doesn't repeat, as shown here.
body
{
background-image: url("CuteCat.jpg");
background-color: SaddleBrown;
color: SeaGreen;
font-size: x-large;
text-shadow: 1px 1px Yellow;
background-position: center;
background-attachment: fixed;
background-repeat: no-repeat;
background-size: 80%;
}
The background-repeat
property is set to no-repeat
so that the browser knows to display just one copy. Because there's just one copy and the image may not be the right size to provide a good presentation when the user resizes the browser, you should also set the background-size
property to resize the image automatically.
3. Save the CSS file as NoRepeat.CSS.
4. Open the BackgroundPosition.HTML
file.
5. Modify the <link>
tag so it looks like this:
<link rel="stylesheet"
href=" NoRepeat.CSS" />
6. Save the HTML file as NoRepeat.HTML.
7. Load the NoRepeat
page.
You see the background shown in Figure 4-12. There’s just one image in the center now — and when you resize the browser, the image automatically resizes as well.
Figure 4-12: Use just one image when presenting larger images.
Creating repetitive borders
One of the more common uses for repetitive images is to create borders made of images. Unfortunately, this technique doesn't work well with Internet Explorer 9. It does work, however, with all newer versions of Chrome, Firefox, and Internet Explorer 10. The following procedure takes the SimpleGraphics
example created earlier and adds a paw-print border to it.
1. Open the SimpleGraphics.HTML
file.
You need to modify the page so that there's a new <div>
to hold the margin, which really isn't part of the image. If you try to attach the margin graphics to the existing image container, the graphics will appear centered on the image container's margin, rather than as full images.
2. Add a new <div>
to the page as shown here.
<div id="BorderContainer">
<div id="ImageContainer">
<img alt="A Picture of a Cute Cat."
title="A Picture of a Cute Cat."
name="CuteCat"
id="CuteCat"
src="CuteCat.JPG" />
<p>A picture of a cute cat!</p>
</div>
</div>
3. Modify the <link>
tag so it looks like this:
<link rel="stylesheet"
href="BorderGraphics.CSS" />
4. Save the HTML file as BorderGraphics.HTML.
5. Open the SimpleGraphics.CSS
file.
You need to change the styles so that they’ll work with the new containers found in the HTML file. Think about the border being a box that encloses a box holding the image and caption. What you get instead of a single image box is a box within a box.
6. Add a new #BorderContainer
style like the one shown here.
#BorderContainer
{
border-style: solid;
border-width: 20px;
border-image:
url(PawPrint.GIF) 25 22 23 fill round;
padding: 24px;
float: left;
position: absolute;
height: 465px;
width: 440px;
left: 50%;
margin-left: -244px;
}
Most of these properties are the same as those originally used for the #ImageContainer
style. The BorderContainer
<div>
is now the outer container, so you position it rather than the ImageContainer
<div>
. There are some changes in measurements to accommodate the size of the border.
The biggest change is the addition of the border-image
property. You supply the URL of the image you want to use, along with the inward offset of the border image, the width of the image, and the image outset. The fill
value tells the browser to fill the <div>
with copies of the image and the round
value tells the browser to resize the image so that an even number of images fill the <div>
.
Figuring out the numbers for a border image can be difficult and time-consuming. Fortunately, you can use the border-image-generator
(http://border-image.com
) to do the work for you. Simply provide the location of the border image you want to use and then use the sliders to figure out optimal values for placing that image around a <div>
. You can copy the results directly from the page to your application.
7. Modify the #ImageContainer
style so that it reflects its new role as an inner container.
#ImageContainer
{
margin: 20px;
height: 420px;
width: 400px;
background-color: White;
}
8. Save the CSS file as BorderGraphics.CSS.
9. Load the BorderGraphics
page.
You see the page shown in Figure 4-13. Notice that the border graphics surround both the image and its caption.
Figure 4-13: Border graphics provide interest for images on your page.