Publishers of technology books, eBooks, and videos for creative people

Home > Articles > Web Design & Development > Usability

Flexible Web Design: Dynamically Changing Images’ Screen Area

📄 Contents

  1. Dynamically Changing Images’ Screen Area
  2. Creating Flexible Collections of Images
  • Print
  • + Share This
There are lots of ways you can dynamically change the screen area that an image takes up. Zoe Mickley Gillenwater explains how.
Like this article? We recommend

No matter how perfectly you build your liquid or elastic layout, it’s not going to work if you don’t make the content within it flexible too. Text is easy—it wraps by default. Images are where it gets tricky. Luckily, as you saw in Chapter 2, there are lots of creative ways to make your images—content images as well as decorative graphic elements—flexible to either the viewport or the text size. In this chapter, you’ll learn the CSS behind those flexible image examples.

Dynamically Changing Images’ Screen Area

Since the area available for an image to display within a flexible layout changes on the fly, your images may need to as well. While fixed-width images can work within flexible layouts—as long as they’re not too large, or you have matching minimum widths in place—there are lots of ways you can dynamically change the screen area that an image takes up.

Foreground Images that Scale with the Layout

One way to dynamically alter the footprint of an image is to make it literally scale. You saw an example of an image that scales with the text in Figure 2.18, and an example of an image scaling with the changing dimensions of its parent element in Figure 2.19. Both are elegant effects that are deceptively simple to create.

Both liquid and elastic scaling images start out with a regular img element in the (X)HTML:

<img src=”styx.jpg” alt=”my cat Styx”>

Notice that this img element has no width or height attributes, as it normally would. You control the dimensions with CSS instead.

For a liquid image, create a CSS rule to set the image’s width to a percentage value:

img {
	width: 50%;
	}

No height value is necessary; the browser determines the height that will proportionately constrain the image’s dimensions. If you were more concerned about making the height of your image stay proportional to its parent’s height than you were with width, you could use the height property in the CSS and leave off the width property. Just make sure not to use the two together.

As with all percentage dimensions, the percentage width value you choose is relative to the width of the parent element. As you change the width of the parent element, the image scales to match (Figure 9.1).

Figure 9.1 The image is set to 50 percent of the width of its parent, the body element, so it always takes up half the width of the viewport.

If you want the image to scale with the text size instead of the width of the parent element, simply change the width value in the CSS to an em value:

img {
	width: 20em;
	}

As we discussed in Chapter 2, any time a browser scales an image, there’s going to be some distortion, but you can keep it minimal by starting out with a very large image so the browser will usually be scaling it down.

Figure 9.2 The image is set to 20 ems, so it will always be roughly 40 text characters wide.

To assure that the browser always scales the image down, not up, you can set a maximum width on the image that matches its set pixel width:

img {
	width: 20em;
	max-width: 500px;
	}

Now the image will scale only until it grows to 500 pixels wide; thereafter it will act as any other fixed-width image (Figure 9.3).

Figure 9.3 The image does not stay proportional to the text size once it reaches its maximum width of 500 pixels.

Hiding and Revealing Portions of Images

Another way to change the amount of screen area an image takes up is to dynamically change how much of the image is shown at any given time. The image itself doesn’t change in size—the amount of space in which it’s allowed to show does, and the rest of the image just remains hidden outside of that space. I call this “variable cropping,” and you saw an example of it in Figure 9.2.

You can create a variable cropping effect with either background or foreground images. Both look the same, but each is specially suited to different situations.

Variable Cropping with Background Images

Putting the image that you want to dynamically crop in the background is ideal when the image is purely decorative. This technique lets you keep the image in the CSS with the other decorative images, so if you later change the look of the site, all the decorative images can be changed in a single style sheet instead of having to replace multiple img elements across multiple pages of the site. By keeping the decorative image as a CSS background, you’re also making it likely that the image won’t print when the user prints the page—background printing is turned off by default in all major browsers—so the user can save ink by printing only content.

To use a CSS background image, you’ll first need an element on which to place the background. This example will use a div:

<div id=”background”></div>

The div is completely empty; it contains no content, but exists simply to hold a background image. If you have a more semantic element you can hang the background on instead, use it. For instance, perhaps the image you want to dynamically crop sits above an h3 element and matches it in width. You could add the image as a background to the h3 element and give the h3 enough top padding to make sure its text sits below the image, not on top of it.

Next, create a rule for this div that sets the image as its non-tiling background:

div#background {
	background: url(styx.jpg) no-repeat;
	border: 2px solid #000;
}

I’ve added a border on to this div as well so you can easily see where its edges lie. Right now, with no content within the div, it will collapse to zero height. Add dimensions to the div to prop it open:

div#background {
	width: 50%;
	height: 330px;
	background: url(styx.jpg) no-repeat;
	border: 2px solid #000;
}

The width is set to some flexible dimension—either a percentage, as I’ve done here, or an em value to make it elastic—so that the div can change in width to show more or less of the image. The height is set to the pixel height of the image so that the entire height of the image will show at all times.

The div will now always be 50 percent as wide as the viewport; its background image doesn’t change in size, but gets cropped to a varying degree from the right side (Figure 9.4).

Figure 9.4 As the width of the browser window decreases, the black-bordered div narrows and cuts off more and more of the right side of its background image.

However, this particular image would look better cropped from the left side, as the cat’s face is on the right side of the photo. To specify from where the image gets cropped, use the background-position property, or its shorthand in the background property, to change the alignment of the image within the div:

div#background {
	width: 50%;
	height: 330px;
	background: url(styx.jpg) no-repeat right;
	border: 2px solid #000;
}

The image is now anchored to the right side of the div, so more or less of its left side shows as the div changes in size (Figure 9.5).

Figure 9.5 With the background anchored to the right side of the div, more of the left side of the image is cut off when the browser window is narrowed.

This is all the CSS necessary to get the basic variable cropping technique working, but you can add a few other enhancements if you like. For instance, right now, once the div exceeds the width of the image, empty white space shows within the div. There are a few ways you could handle this. You could add a background color to the div as well that would fill up whatever space the image cannot; if you blend the edge of the image into this background color, the effect can look seamless, as in Figures 2.16 and 2.17. Or, you could add a maximum width to the div so it can never grow larger than the image. You could also add minimum widths, as well as maximum and minimum heights, to ensure that the div can never grow or shrink past particular points in the image.

Variable Cropping with Foreground Images

If the image that you want to dynamically crop is functional content, you’ll want to keep it as a foreground image by placing it in the (X)HTML using the img element. You can ask yourself these questions to determine if the image is content, not decoration:

  • Does the image convey information that I ought to put as text in an alt attribute?
  • Do I want to make sure the image always prints because without it the printout wouldn’t make sense or be complete?
  • Do I want to link the image?

If the answer to any of these questions is yes, the image is content and should be kept in the (X)HTML. CSS background images can’t achieve any of these goals—at least not without some complicated workarounds and hacks, all of which are quite silly, considering how easily a simple img element can achieve all this.

As with the background-image version of the variable cropping technique, you’ll need some block element in the (X)HTML to hold the image. We’ll use a div again; this time it won’t be empty, but will instead contain the img element:

<div id=”foreground”>
	<img src=”styx.jpg” alt=”my cat Styx” width=”500” height=”330”>
</div>

Just as before, the div needs to have a flexible width and a height set to the pixel height of the image:

div#foreground {
	width: 50%;
	height: 330px;
	border: 2px solid #000;
}

So far, all we have is a regular div holding a regular image—there’s nothing yet that makes this a variable cropping technique. If the image is bigger than the div, it doesn’t get cropped, but simply overflows (Figure 9.6).

Figure 9.6 The image inside the div hangs out the right side of the div, overlapping its black borders, when the div becomes narrower than the image.

To get the cropping effect, add overflow: hidden; to the CSS rule:

div#foreground {
	overflow: hidden;
	width: 50%;
	height: 330px;
	border: 2px solid #000;
}

Now whatever portion of the image would overflow out of the div is hidden from view (Figure 9.7).

Figure 9.7 With overflow set to hidden, the extra portion of the image is now hidden from view.

Once again, though, it would be better for this image to be cropped from the left side, not the right. We can’t use the background-position property this time because it’s not a background image. To change how a foreground image is anchored within its parent, you can float the image:

div#foreground img {
	float: right;
}

This anchors the image to the right side of the div, so more or less of its left side shows as the div changes in size. Using a foreground image results in an effect that looks exactly like using a background image (seen in Figure 9.5), but the foreground image has alternative text, and you could also easily add a link to it.

Creating Sliding Composite Images

Perhaps you don’t want either end of your image dynamically cropped off—there may be important content on each side that you want to always keep in view. You could scale the entire image instead, which would keep the entire width of the image always visible, but it would also change the vertical space the image takes up, and perhaps you don’t want this either. This is the perfect time to try using what I call a composite image.

Creating what appears to be a single image out of multiple pieces that slide over and away from each other takes a little more work on the graphics side than the variable width image techniques we’ve gone over so far. The real-web-site example of this composite image technique shown in Figures 2.23 and 2.24 used two images to create the effect; you can use an unlimited number of images, but we’ll keep it simple and use two for our own alien-invasion example as well.

One image is going to be at least partially overlapping the other, so at least the topmost image needs to have a transparent background. (You may choose to make the lower image transparent too, to allow parts of the main page background to show through, for instance.) You can use either a GIF with index transparency or a PNG with alpha transparency. PNGs are more versatile, since they can lay over any other color or pattern without the skinny colored edge that shows around GIF images when they’re placed over something that’s a different color than they were optimized for. PNGs can also have variable degrees of transparency, instead of each pixel being either 100 percent transparent or 100 percent opaque.

We’ll use an alpha-transparent PNG for our top image in this example. Figure 9.8 shows our flying saucer image in Adobe Fireworks; the checkerboard background indicates the transparent areas of the image. Figure 9.9 shows the image that the flying saucer will be laid on top of—a photo of the Chicago skyline—which can be saved as an ordinary JPG.

Figure 9.8 The flying saucer image has large areas of partial or total transparency through which the skyline image will be visible.

Figure 9.9 The skyline image is completely separate from the flying saucer image.

Once you have your images made, you need two block elements to place each on as a background image. One block element needs to be nested inside the other. In a real page, you’d want to make use of block elements that were already in place as much as possible, such as existing wrapper and header divs. For this simple example, we’ll use two empty divs:

<div id=”outer”><div id=”inner”></div></div>

Next, you need to create rules placing each image as a non-repeating background on each div, with the image you want on the bottom used for the background of the outer div:

#outer {
	background: url(skyline.jpg) no-repeat;
}
#inner {
	background: url(ufo.png) no-repeat;
}

Since the divs are empty, they also need dimensions added to them to stop them from collapsing entirely, as well as to create the flexible behavior that we want:

#outer {
	width: 100%;
	max-width: 1000px;
	height: 300px;
	background: url(skyline.jpg) no-repeat;
}
#inner {
	width: 100px;
	height: 250px;
	background: url(ufo.png) no-repeat;
}

Both of the images now show on the page, with the flying saucer layered over the skyline (Figure 9.10). However, the flying saucer never moves when the window changes in size—it’s always pinned to the top left corner of the skyline photo. That’s because the div for which it’s a background begins in that corner, and non-repeating, non-positioned background images display in the top left corner by default.

Figure 9.10 The flying saucer image is layered over the skyline image to create the appearance of a single image, but the flying saucer isn’t yet in the place we want it.

There are a couple ways to fix this: use the background-position property to change where the flying saucer displays within the div, or move the entire div. Either option is fine, but the latter seems a little easier to understand and implement—at least to me—so that’s what we’ll use here.

We’ll move the div using absolute positioning; floating would work as well. First, add position: relative; to the #outer rule to make that div act as the containing element for the absolutely positioned inner div. Then, add position: absolute; as well as top and right values to the #inner rule:

#inner {
	position: absolute;
	top: 50px;
	right: 50px;
	width: 100px;
	height: 250px;
	background: url(ufo.png) no-repeat;
}

Now the flying saucer image will always be 50 pixels away from both the top and right edges of the skyline photo. Because the outer div has a flexible width, its right edge moves as the window is resized, which in turn makes the flying saucer image move as well (Figure 9.11).

Figure 9.11 The flying saucer image now appears to move as the browser window changes in size.

  • + Share This
  • 🔖 Save To Your Account

Peachpit Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from Peachpit and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about Peachpit products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites; develop new products and services; conduct educational research; and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email ask@peachpit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by Adobe Press. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.peachpit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020