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

Home > Articles

This chapter is from the book

This chapter is from the book

Common Background Properties

Since CSS1, CSS has provided a number of properties that let us style the background of an element.

It may seem an obvious thing, but before we go on, just what is an element's background? We'll see in a moment that every element has its own box that contains its content; the box includes margin, border, padding, and content, as shown in figure 4.3.

4-3

4.3 The box of an element is a rectangle, with margin, padding, border, and content. Note that margin, padding, and border widths and heights may all be zero.

The background of an element starts inside the border box—so applying a background color or image to an element does not apply the background to its margin, as demonstrated in figure 4.4.

4-4

4.4 The background of an element starts at its border box and does not fill the margin.

CSS3 lets developers specify where the background starts, both horizontally and vertically: the border box, padding box, or content box are all options, but the margin box is not. Alas, this and other advanced background properties like multiple background images are not yet widely supported in browsers and can be difficult to use with progressive enhancement.

background-color

The background-color property specifies the color of the background of an element. It can take all of the values that we saw for the color property, and one more—the keyword value transparent (note that this value is not valid for the color property). A transparent background-color means that the content "behind" the element is visible through the element. We'll look at how to create semi-transparent backgrounds using CSS3 in Chapter 13. To create a light gray background on an element, we use a statement like this:

p {
  background-color: #b3b3b3
}

It's important, when specifying a background color, to ensure sufficient contrast with the text color so that the text will be legible. We look at this issue in some more detail in Chapter 6, but one good practice is to make sure you always specify a color when you specify a background color (the CSS validator will give you a warning to this effect).

background-image

The background-image property, which specifies a background image for an element, is one of the most commonly used features of CSS. It can be used to create patterned backgrounds behind whole pages or large sections of a page; to add icons (such as a PDF icon for a link to a PDF file); even to add "bullets" to lists—although there's another a property designed expressly for this purpose.

A background image might be a single large image, or an image that's tiled horizontally, vertically, or both. Background images can be positioned anywhere on the background of an image, though only in CSS3 can they be resized, and this feature has little support in browsers, so is as yet of little real-world value.

A background image is added to an element using the background-image property. This takes a URL value, which is a relative or absolute URL for the image file. The PNG, GIF, and JPEG formats are supported in all browsers, though some browsers also support other formats (such as PDF in Safari and SVG in Opera). Because of the limited support for formats other than these three main formats, only these formats should be used in most situations. As mentioned with the HTML img element in the last chapter, PNG is to be preferred for non-photographic images, and JPEG for photographic images.

URL Values

URL values in CSS have the form of a relative or absolute URL inside parentheses, and are preceded by the string url wrapped in single or double quotation marks, like this:

url("path/to/image.png")
               

Here we'll add the background image in figure 4.5 to the body element:

body {
  background-image: url("./images/shadow.png");
}
4-5

4.5 The background image for our body element

And here's the effect [4.6], which is almost certainly not what we want.

4-6

4.6 Our background image, tiled horizontally and vertically

background-repeat

So what's going on here? By default, a background image repeats both horizontally and vertically, creating a tiling effect. In this case, that's not what we want. The effect we are trying to achieve is a shadow on the right-hand side of the page. So, we'll need to repeat the image vertically but not horizontally. We can specify how an image repeats with the background-repeat property. This property takes one of these keyword values:

  • repeatThe default value that repeats the image in both directions.
  • no-repeatMeans the image is only shown once.
  • repeat-xThe image is repeated horizontally but not vertically.
  • repeat-yThe image is repeated vertically but not horizontally.

In this instance, we want to repeat vertically, so we'll use background-repeat: repeat-y [4.7].

4-7

4.7 Our shadow image, repeated vertically

If you can't make out where the shadow has gone, it's now down the left-hand side of the page. What we want to do is position it down the right-hand side of the element, which we can do with background-position.

background-position

The background-position property lets us specify where the image will be placed, or if it is repeated, where the repeat starts from. We can specify the position of a background image for an element in a number of ways.

Keywords

The background-position property can take one or two keywords. If a single keyword is used, it applies to both horizontal and vertical position. If two keywords are used, the first applies to horizontal position, and the second applies to vertical position. Regardless of the keyword chosen, it's important to note that the image tiles to fill the background horizontally, vertically, or in both directions. The keywords are:

  • topThe image is placed, or repeats, vertically from the top down.
  • centerThe image is placed, or repeats, horizontally from the center of the element left and right, and vertically from the center of the element up and down. Note that the background image when repeated always repeats in both directions (up and down, or left and right).
  • bottomThe image is placed, or repeats, vertically from the bottom up.
  • leftThe image is placed, or repeats, horizontally from the left-hand side of the element to the right.
  • rightThe image is placed, or repeats, horizontally from the right-hand side of the element to the left.

In this instance, we want the element to be repeated from the top down, and to be placed at the right-hand side of the element. We'd do this by using background-position: right top.

Length Values

It's possible to explicitly specify where the image will be placed or repeated from with one or two length values. For example, we might specify that a background image is placed 5 em from the left edge of an element using background-position: 5em.

With length values, unless the width of our element is fixed, it's not possible to achieve the objective of putting the image at the right side of the element.

Percentage Values

A particularly technical way we can specify background image position is using percentage values. Unlike length values, where the value specifies a vertical or horizontal offset for the top or left of the element, percentages are more subtle again.

With a percentage value of, for example, 60%:

background-position: 60%
               

we aren't specifying that the left edge of the background image is 60% from the left edge of the element, but that a point 60% from the left edge of the image horizontally is aligned with a point 60% from the left edge of the element horizontally, as shown in figure 4.8.

4-8

4.8 Percentage background-position values align a point on the background image with a point on the element.

Figure 4.9 shows these different positioning approaches together.

4-9

4.9 background-position with keywords, length values, and percentages

Although it sounds quite complex, it gives great flexibility when aligning background images with their elements. In the current situation, where we are looking to put the shadow image at the right of the element, we can use background-position: 100%.

This doesn't put the left-hand edge of the image 100% across the background of the element—which would essentially hide the image to the right of the element—but rather aligns the point 100% across the image with the point 100% across the element, so that their right edges are aligned.

Figure 4.10 shows our page with the shadow now aligned with the right edge of the body element.

4-10

4.10 The shadow image aligns with the right edge of the body element.

background-attach

With the current example it might not make much sense, but it's possible to "fix" an image on the background, so that when the content of the element is scrolled, the image remains fixed in its location on the background. We do this with the background-attach property, which takes two possible keyword values: scroll and fix. For example, if we had a single large watermark-style image as the background of a page:

body {
  background-image: url('../watermark.png');
  background-repeat: no-repeat;
  background-position: center;
  background-attach: fix
}

then, when the page is scrolled, the watermark remains horizontally and vertically centered on the page, and the text and other content of the page scrolls over the top of it. scroll is the default value for the property.

CSS3 Background Properties

CSS3 introduces several new background properties, including the ability to specify multiple background images (we cover this in Chapter 13), to resize the background image, and to specify where the image fills from—the border, padding, or content box, not just the padding box, as is the case now. As noted briefly, none of these properties is very widely supported in contemporary browsers and should be used very carefully if at all at present, as their use can easily render content unreadable.

Shorthand Properties

CSS provides a way for some sets of properties to be specified with a single shorthand. For example, we can specify all of the background properties for a single statement with the one shorthand property background. We simply put each of the individual values separated with spaces as the value for the shorthand. For example, our shadow shorthand would look like this:

background: url('../shadow.png') repeat-y top right;

It's important not to mix shorthand and regular properties in a single statement. When you use a shorthand, all of the properties associated with that shorthand are applied—including defaults for any property you've not explicitly set a value for in the shorthand. In our example, the default value of background-attach (scroll) would be specified even though we've not set it explicitly. Why is this important? Well, if you'd previously specified a background-attach value of fix in the same statement, the shorthand overrides this, because the shorthand is further down the style sheet. This is a subtle problem that can catch developers and cause considerable confusion. The best way to avoid it is to use either shorthand or "longhand" properties, but to not mix them together.

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