Lesson 5

Backgrounds & Gradients

Backgrounds are an important part to CSS as they allow you to easily change the composition of an element. They can be used for decoration while setting the scene within an element. They can provide visual context for an element’s content, enhancing usability. With use cases large and small, backgrounds have a significant impact on the overall design of a website.

Adding a background to an element can be accomplished in a few different ways, most often in the form of a solid color, an image, or a combination of the two. The ability to control exactly how a background is implemented on an element provides greater direction to the overall appearance.

With CSS3, new backgrounds and capabilities were introduced, including the ability to include gradient backgrounds and multiple background images on a single element. These progressions are becoming widely supported within all browsers and expand the possibilities of modern web design.

Adding a Background Color

The quickest way to add a background to an element is to add a single color background using the background or background-color property. The background property accepts colors and images, while the background-color property is used strictly for background colors. Either property will work, which one you decide to use depends on your preference and the case in which it is being used.

div {
  background: #f60;
  background-color: #f60;
}

When declaring a background color you have a few different options as far as what value to use. As with other color values, you can pick from keywords, hexadecimals, RGB, RGBa, HSL, and HLSa. Most commonly seen are hexadecimal values, however it is important to note RGBa and HLSa. These color spectrums allow us to use opacity within our background via an alpha channel. If we are looking to use a 30% opaque black we can use rgba(0, 0, 0, 0.3). These opaque backgrounds open a whole new level of control. As a word of caution, RGBa and HLSa are not supported by every browser so it is important to provide a fall back CSS declaration above the declaration using an opaque value.

div {
  background: #b2b2b2;
  background: rgba(0, 0, 0, 0.3);
}

Adding a Background Image

On top of adding a background color to an element you can also add a background image. Background images work similarly to background color, however they also offer a few additional properties to finesse the images. As before, you can use the background property or the background-image property. No matter which property you use there must be an image source identified using the url value. The url value should be the background image’s path.

div {
  background: url('alert.png');
  background-image: url('alert.png');
}

Marking up an image solely using the url value could provide undesirable results as it will repeat horizontally and vertically from the top left of the containing element. Thankfully we can use the background-repeat and background-position properties to straighten things out.

Background Repeat

By default, a background image will repeat indefinitely, both vertically and horizontally, unless specified. Specifying a background repeat value can be done by adding it in after the url value on the background property or by using the background-repeat property itself.

div {
  background: url('alert.png') no-repeat;
  background-image: url('alert.png');
  background-repeat: no-repeat;
}

The background repeat takes four different values repeat, repeat-x, repeat-y, and no-repeat. The repeat value is set by default and will repeat an image both vertically and horizontally. repeat-x will repeat the image horizontally and repeat-y will repeat the image vertically. no-repeat simply means: display the background image once and do not repeat at all.

Background Position

Using the background-position property you can control exactly where the background image is placed or repeated from. As with the other background properties, a background position may be added using the background property after the url value: or with the background-position property itself.

div {
  background: url('alert.png') 10px 10px no-repeat;
  background-image: url('alert.png');
  background-position: 10px 10px;
  background-repeat: no-repeat;
}

The background position requires two values, a horizontal offset (first) and a vertical offset (last). To set a background position value you can use the top, right, bottom, left keywords, pixels, percentages, and other length measurements. Keywords and percentages work very similarly. The keywords top left are identical to the percentages 0 0, and the keywords right bottom are identical to the percentages 100% 100%. One added value of percentages over keywords is the ability to center a background image by using 50% as a value. To center the background image at the top of an element you could use the value 50% 0. Using pixels for a background position is also popular, as pixels give you exact control of where your background will be positioned.

Background Percentages
Fig. 5.01 Using percentages and keywords to position a background image.

Alert Message Background Example

HTML
<p><strong>Warning!</strong> You are walking on thin ice.</p>
CSS
p {
  background: #fff6cc url('warning.png') 15px 50% no-repeat;
  border-radius: 6px;
  border: 1px solid #ffd100;
  color: #000;
  padding: 10px 10px 10px 38px;
}

Demo

Warning! You are walking on thin ice.

Gradient Backgrounds with CSS3

Gradient backgrounds were introduced with CSS3, and praise rang out among designers and developers. Although gradient backgrounds do not work in every browser, they are currently supported by all modern browsers.

Gradient backgrounds are treated as a background image. You can create a gradient using the background or background-image properties just like you would a regular background image. The value for these properties vary a little depending on what type of gradient you are looking for: linear or radial.

Browser Specific Property Values

As CSS3 was introduced browsers began to slowly support different features, each browser maker implementing new properties in a slightly different way. In doing so browsers used vendor prefixes to establish exactly how their features should look and perform. Gradient backgrounds took the brunt of this as each browser had its own preferred method for gradient values. Fortunately, most browsers have settled on a standard, however it is still worth outlining support for all of them as a fall back.

While vendor prefixes are becoming less relevant it still doesn’t hurt to use them for older browsers.

  • Mozilla Firefox: -moz-
  • Microsoft Internet Explorer: -ms-
  • Opera: -o-
  • Webkit (Chrome & Safari): -webkit-

Linear Gradient Background

For years designers and developers have been cutting up image files and using them as linear gradient backgrounds. The process worked, but took a while to implement and was difficult to change. Fortunately, those days are gone and linear gradient backgrounds can now be specified within CSS. If a color needs changed, there is no need to recut an image and upload it to the server. Now all that is needed is a quick fix within CSS. Beautiful.

div {
  background: #70bf32;
  background: url('linear-gradient.png') 0 0 repeat-x;
  background: -webkit-linear-gradient(#a1e048, #6a942f);
  background:    -moz-linear-gradient(#a1e048, #6a942f);
  background:     -ms-linear-gradient(#a1e048, #6a942f);
  background:      -o-linear-gradient(#a1e048, #6a942f);
  background:         linear-gradient(#a1e048, #6a942f);
}

Linear Gradient Background

Above is a breakdown of all of the different vendor prefixes and how linear gradient backgrounds are supported. As you could guess the linear-gradient(#8ec63f, #45611f) value has become the most supported and thus the standard. Moving forward, including radial gradients, we’ll use this formatting but don’t forget the other values when working on your own projects.

By default linear gradients move from the top to the bottom of an element. The direction may be changed with the use of keywords or a degree value stated before any color values. For example, should you want a gradient to move left to right they keyword value to right may be used to identify in which direction the linear gradient should progress. Additionally, keyword values may also be combined. Should you want the gradient to move from the top left to the bottom right of an element the keyword value of to bottom right may be used.

div {
  background: linear-gradient(to bottom right, #a1e048, #6a942f);
}

When using a diagonal gradient on an element that isn’t exactly square the gradient will not proceed directly from one corner to the other. Instead, the gradient will identify the absolute center of the element, place anchors in the perpendicular corners from where it should progress, and then move in the general direction of the corner outlined within the value. These corners in which the gradient moves towards are called “magic corners” as they are not absolute. Eric Meyer has done a wonderful job of outlining this syntax.

On top of keywords, degrees are also an acceptable value. If you want your gradient to start from the left top you can use a the degree value 315deg.

Old Linear Gradient Keyword Syntax

Previously the keyword syntax for linear gradients did not require the use of the keyword to. Instead the keyword, or keywords, stated would identify the starting point for the gradient and it would then progress in the opposites direction. In the diagonal linear gradient example above the old syntax would be top left, not to bottom right.

The new keyword syntax is still gaining support amongst different browsers. Should the new syntax not work for you it may be worth checking to see if the old syntax does, however keeping in mind that it should be updated in time.

Radial Gradient Background

While the linear gradient is perfect for building a gradient propagating in one direction, often the need for a radial gradient arises. Radial background gradients work just like linear gradients and share a lot of the same values. However, radial gradients can be quite complex with values for location, size, radius, and more. We’ll cover the basics, but please feel free to take a deeper dive into radial gradients.

div {
  background: #70bf32;
  background: url('radial-gradient.png') 50% 50% no-repeat;
  background: radial-gradient(#a1e048, #6a942f);
}

Radial Gradient Background

CSS3 Gradient Background Generator

Programming CSS3 gradients from hand can be quite a task, especially if you are not all that familiar with them. Fortunately, quite a few CSS3 gradient generators have popped up. Each generator works a little differently, some coming with presets and examples and some having an expansive list of options. If interested, I recommend doing some research to find the right generator for your needs.

Gradient Background Stops

So far we have discussed transitioning a gradient from one color to another, however if you want to transition more than two colors you can use color stops. Instead of declaring two color values, you can declare numerous values. The browser will transition from one to the next accordingly. Adding a length value to these color stops determines at what position and distance the transition will take place. If no length value is declared the gradient will transition evenly between all colors declared.

div {
  background: #6c9730;
  background: url('linear-gradient-stops.png') 0 0 repeat-y;
  background: linear-gradient(to right, #8dc63f, #d8ad45, #3b4b94);
}

Gradient Background Stops

Navigation Background Example

HTML
<ul>
  <li class="play"><a href="#">Play</a></li>
  <li class="back"><a href="#">Skip Backward</a></li>
  <li class="stop"><a href="#">Pause/Stop</a></li>
  <li class="forward"><a href="#">Skip Forward</a></li>
</ul>
CSS
ul {
  background: #f4f4f4;
  background: linear-gradient(#fff, #eee);
  border: 1px solid #ccc;
  border-radius: 6px;
  display: inline-block;
  height: 22px;
  list-style: none;
  margin: 0 0 20px 0;
  padding: 0 4px 0 0;
}
li {
  height: 16px;
  float: left;
  padding: 3px;
  text-indent: -9999px;
  width: 16px;
}
.play {
  background: #f4f4f4;
  background: linear-gradient(#fff, #eee);
  border: 1px solid #ccc;
  border-radius: 30px;
  left: -4px;
  padding: 7px;
  position: relative;
  top: -5px;
}
li a {
  background: url('controls.png') 0 0 no-repeat;
  display: block;
  height: 16px;
  width: 16px;
}
.play a:hover {
  background-position: 0 -16px;
}
.back a {
  background-position: -16px 0;
}
.back a:hover {
  background-position: -16px -16px;
}
.stop a {
  background-position: -32px 0;
}
.stop a:hover {
  background-position: -32px -16px;
}
.forward a {
  background-position: -48px 0;
}
.forward a:hover {
  background-position: -48px -16px;
}

Demo

Multiple Background Images with CSS3

It used to be if you wanted an element to have more than one background you would have to wrap it with another element and assign a background to the wrapping element. This created bloated code for the simple use of adding additional backgrounds. Now with CSS3 we can use multiple background images on a single element by chaining these background values together.

div {
  background:
    url('foreground.png') no-repeat 0 0,
    url('middle-ground.png') no-repeat 0 0,
    url('background.png') no-repeat 0 0;
}

Not only can you chain background property values, you can also chain together background-repeat, background-position, and other background related properties.

Multiple Background Images Example

HTML
<div>Dinosaur with Grass and Clouds</div>
CSS
div {
  background: 
    url('dyno.png') no-repeat 380px 18px, 
    url('grass.png') no-repeat 0 100%, 
    url('sky.jpg') no-repeat 0 0;
  border-radius: 6px;
  height: 200px;
}

Demo

Dinosaur with Grass and Clouds

New CSS3 Background Properties

Along with gradient backgrounds and multiple background images, CSS3 also introduces three new CSS properties, background-size, background-clip, and background-origin.

CSS3 Background Size

The background-size property allows you to specify a specific size for your background image. The first value declared is the width of the image and the second value is the height. These values may include any length measurement or keyword, most notably pixels and percentages. If only one value is declared, the auto keyword may be used to keep the proper image proportions.

div {
  background: url('shay.jpg') 0 0 no-repeat;
  background-size: 85% auto;
  border: 1px dashed #8c9198;
  height: 240px;
  width: 200px;
}

Cover & Contain Values

The cover keyword value specifies that the background image should be resized proportionally to completely cover an element. How the background will be resized depends on the dimensions of the background and element. While the background will hold its dimensions proportionally, the quality of the image may be resized in a way that it distorts the image. Always make sure to check your work.

The contain keyword value will resize a background image proportionally to keep it within the confines of the element. This may mean that there are parts of the element without a background, however the entire background image will be visible. As with the cover keyword value, the resizing of the background image will be proportional to the image’s dimensions, however it may result in a distorted image.

Shay Howe
Fig. 5.02 Using percentages and keywords to position a background image.

CSS3 Background Clip & Background Origin

The background-clip property specifies the area a background image will cover and the background-origin property specifies where the background-position should originate. The introduction of these two new properties also includes three new values: border-box, padding-box, and content-box. Each of these three values may be used to set a value for the background-clip and background-origin properties.

Background Clip & Origindiv {
  background: url('shay.jpg') 0 0 no-repeat;
  background-clip: padding-box;
  background-origin: border-box;
}
Border Box Value
Fig. 5.03 The border-box value extends into the border of an element.
Padding Box Value
Fig. 5.04 The padding-box value extends into the padding of an element, but is contained within any border.
Content Box Value
Fig. 5.05 The content-box value is contained within the border and padding of an element.

Resources & Links

Complete! Any questions?

Please feel free to contact me on Twitter if you have any questions. Also, if you enjoyed this lesson please share it with your friends.

An Advanced Guide to HTML & CSS

An Advanced Guide to HTML & CSS

An Advanced Guide to HTML & CSS takes a deeper look at front-end design & development, teaching the latest for any designer looking to round out their skills.

View the Advanced Guide to HTML & CSS