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

Home > Articles > Web Design & Development > CSS

This chapter is from the book

This chapter is from the book

Bring the Bling with CSS Gradients

Gradients are one of the most hotly anticipated features to become native to CSS. Gradients are vital for design in general to reproduce the effects of light falling on curved/shiny surfaces and create interesting patterns. The number of developers who use them in web design is staggering, if not unsurprising. What is a surprise is that until CSS3 came along, web developers never had the ability to create gradients programmatically in any sane way that would work across browsers. SVG had gradients for a long time before that, but IE never supported SVG until IE9.

All this time you’ve been stuck with either faking SVG in IE using a Polyfill solution like SVGWeb or using repeated background images for those gradients or repeating patterns you desired. This last technique works OK-ish but is an inflexible pain and can become cumbersome very quickly, especially if your boss keeps changing his mind about the gradient colors (more playing with Photoshop; oh goody) or if you are trying to create any kind of complicated layered effect.

Again, CSS3 comes to the rescue with linear and radial gradients, which are defined in the CSS Image Values and Replaced Content module (http://dev.w3.org/csswg/css3-images). To see how flexible CSS gradients are, just have a good play with the examples in this section.

Let’s review the two different gradient types separately.

Linear Gradients

Linear gradients are the simpler of the two types; these are smooth color progressions that start at one side or corner of an area and cycle smoothly between two or more color stops, ending at the other side or corner.

In CSS they work the same. CSS gradients are basically a special kind of background image. You can set them in place of an image in most places that it would make sense to do so; for example, background-image and border-image (see the “Box Clever: border-image” section later in this chapter for more on border images).

The most common place you’ll want to use them is on standard, commonplace backgrounds. Here is a simple syntax example:

background: linear-gradient(#ff0000,#007700);

Figure 4.12 shows the result, taken from an example file in the chapter4 code download folder called linear-gradient-test.html. The two colors are the start color in the gradient and the end color, and by default the gradient runs from the top to the bottom of the container.

Figure 4.12

Figure 4.12 A basic linear gradient.

Linear Gradient Direction

If you want to vary the direction of your gradient, you can add a direction value at the start of the gradient, like this:

background: linear-gradient(to bottom right, #ff0000,#007700);

This direction value makes the gradient travel from the top left to the bottom right (Figure 4.13).

Figure 4.13

Figure 4.13 A linear gradient direction can be varied via the use of keywords or degree values.

As you’d expect, you can use a whole range of logical keywords for gradient direction: to top, to top right, to right, to bottom right, to bottom, to bottom left, to left, to top left.

You can also specify the direction you want the gradient to travel in using an angle. Zero degrees (0deg) is the equivalent of to right; as you increase the angle, it travels around counterclockwise. So the subsequent equivalents would be 90deg = to top, 180deg = to left, 270deg = to bottom. Bear in mind that 135deg will not be the equivalent of to top left (as you might expect) unless the container is a perfect square: The diagonal keywords will change the angle so the gradient will always run from one corner to the other. As a result, you can choose keywords or angles, depending on the effect you want to create.

Note: The spec states that 0deg is the equivalent of the keywords to top, but browsers don’t follow this currently. This could change in the future.

Linear Gradient Color Stops

You can also add multiple color stops between the start and the end point by putting them between the start and end color stops, like this:

background: linear-gradient(to right,#ff0000,#0000ff 40%, #000000 70%,#007700);

The result is shown in Figure 4.15.

Figure 4.15

Figure 4.15 A gradient with multiple color stops.

The unit values specify the distance away from the start of the gradient. Note that the percentage values are optional: If you don’t specify them, the color stops will be evenly spaced along the gradient.

Instead of percentages, you can use any units you like that would make sense in the circumstances. By default, the first and last values are at 0% and 100%, but you can alter their positions too. For example:

background: linear-gradient(#ff0000 66px, #ffffff 67px, #ffffff 133px, #00ff00 134px);

This effect creates three solid color bands from left to right (Figure 4.16). The green color stop is set at 66px down from the top, and everything before it adopts the same color. The red color stop is set at 134px, and everything after it adopts the same color. I also inserted two white color stops in the middle to force the middle band to be completely white. This technique is very useful, especially if you want to start creating more intricate and interesting repeating background patterns, as you’ll read about later in the “Multiple Backgrounds” section.

Figure 4.16

Figure 4.16 Italiano, pasta, meatballs, Roma Roma (well, not quite).

You can even use negative unit values if for some reason you want the linear gradient to start or end outside the container. (You might want to change the gradient on hover. Unfortunately, you can’t smoothly animate a gradient, at least not at the time of this writing. Believe me, I’ve tried.)

Again, I’ll extol the awesomeness of transparent colors by providing a very simple gradient with a vital difference (Figure 4.17):

background: linear-gradient(to top right, rgba(0,0,0,0.6),rgba(0,0,0,0));
background-color: #ff0000;
Figure 4.17

Figure 4.17 RGBA colors provide great control over gradients while blending them into their surroundings.

Here the gradient is a transparency gradient overlaid onto a solid background color to create the different gradient colors. This is a very powerful technique because it means you can control the look of an entire site section just by varying the background color. It’s perfect if you want to vary the look of different pages on a site with minimum effort. Try it!

Repeating Linear Gradients

Repeating linear gradients have a similar syntax to linear gradients. Look at the following example and the result in Figure 4.18:

background: repeating-linear-gradient(to top right, rgba(0,0,0,0.4) 10px ,rgba(0,0,0,0) 20px, rgba(0,0,0,0.4) 30px);
background-color: #ff0000;
Figure 4.18

Figure 4.18 A simple repeating gradient.

Only 30 pixels’ worth of gradient has been specified, but it is repeated over and over again until the end of the container is reached.

Radial Gradients

Radial gradients work a bit differently than linear gradients. Instead of traveling across a container from one side to another, they radiate outwards from a single point. Here is a simple example:

background: radial-gradient(50% 50%, 60% 60%, rgb(75, 75, 255), rgb(0, 0, 0));

This produces the result shown in Figure 4.19 (if you want to experiment with this code, download the radial-gradient-test.html file in the chapter4 folder).

Figure 4.19

Figure 4.19 A simple radial gradient.

The syntax is a little different than that of linear gradients, so let’s go through the radial gradient syntax step by step.

Radial Gradient Position

The first two values in the syntax (50% 50% in the preceding code) dictate the location of the origin of the radial gradient: The first value is the horizontal position inside the container, and the second value is the vertical. In the preceding example, the radial gradient equates to 50% across from the left side and 50% down from the top, which places it slap bang in the middle of the container. As with linear gradients, you can use any unit values that make sense, even negative unit values.

You can also use keywords in place of unit values in the same manner as you learned earlier but with the addition of center if you want the horizontal or vertical position to be centered in the container (this doesn’t make sense for linear gradients, but it does for radial gradients). Figure 4.20 shows a few examples.

Figure 4.20

Figure 4.20 From left to right:top left, bottom center, and right positioning of a gradient. When only one keyword is supplied, it is assumed to be the horizontal keyword, and the vertical one is given a value of center.

Radial Gradient Size and Shape

The second set of values in the radial gradient syntax (60% 60% in the example) dictates the size of the gradient—the horizontal and vertical radius size. Because you are working with the radius rather than the diameter, 50% or 60% will produce a nice spread across a container. 100% would be double the width/height of the container, swamping it entirely, which may or may not be the effect you want (Figure 4.21).

Figure 4.21

Figure 4.21background: radial-gradient(50% 50%, 100% 100%, rgb(75, 75, 255), rgb(0, 0, 0)); swamps the container.

Again, to set these values, you can use any units that make sense. You can also use different values for the horizontal and vertical radii, for example:

background: radial-gradient(50% 50%, 70% 40%, rgb(75, 75, 255), rgb(0, 0, 0));

This effect is shown in Figure 4.22.

Figure 4.22

Figure 4.22 Creating an ellipse using different vertical and horizontal radius values. Neo’s amphetamine lunch?

But as usual, there are more ways to set the radii: CSS3 supplies several keywords for setting the radii, which need explaining because they are a bit confusing. Consider the following examples (Figure 4.23):

background: -o-radial-gradient(30% 50%, circle closest-side, rgb(75, 75, 255), rgb(0, 0, 0));
background: -o-radial-gradient(30% 50%, ellipse closest-side, rgb(75, 75, 255), rgb(0, 0, 0));
Figure 4.23

Figure 4.23 The effects of circle closest-side and ellipse closest-side.

So, what’s going on here? By using circle and ellipse, you specify that you want your gradient to be a circle or an ellipse, respectively. closest-side means that the shape will expand so that it just touches the container side closest to the point of origin of the radius in the case of a circle and the horizontal and vertical container sides closest to the point of origin of the radius in the case of an ellipse.

Other keyword combinations available to you include:

  • closest-corner positions the gradient so that its edge just touches the corner of the element closest to the origin (Figure 4.24).
    Figure 4.24

    Figure 4.24 The effects of circle closest-corner andellipse closest-corner.

  • farthest-side positions the gradient so that its edge touches the side of the element farthest from its centre in the case of a circle or the farthest horizontal and vertical sides in the case of an ellipse (Figure 4.25).
    Figure 4.25

    Figure 4.25 The effects of circle farthest-side and ellipse farthest-side.

  • farthest-corner positions the gradient so that its edge just touches the corner of the element farthest from the origin. You can use the keyword cover in place of farthest-corner (Figure 4.26).
    Figure 4.26

    Figure 4.26 The effects of circle farthest-corner and ellipse farthest-corner.

I’ve not used these implicit shape values very much, preferring instead to control the shape using explicit unit values. But this doesn’t mean you won’t.

Radial Gradient Color Stops

Color stops work in the same way as the color stops in linear gradients except that the units you specify denote distance from the center of the gradient, not distance from the starting corner/edge.

I encourage you to experiment with different color values with the examples I’ve provided and otherwise. Try creating a sun’s rays or a shadow or flashlight moving across the top of your site. Again, use RGBA colors for the win! You’ll see more exciting examples throughout the book.

Repeating-Radial-Gradient

As with linear gradients, you can also create repeating radial gradients by adding repeating values into the syntax (Figure 4.27):

background: -o-repeating-radial-gradient(50% 50%, 60% 60%, rgba(75, 75, 255,0.5) 10px, rgba(0, 0, 0,0.5) 20px);
background-color: #ff0000;
Figure 4.27

Figure 4.27 A simple repeating radial gradient.

Providing Gradient Support for Old Versions of IE

CSS3PIE also adds support for CSS gradients. But again, you need to be careful of its limited RGBA support. To use CSS3PIE, target a separate, nontransparent color gradient to IE using a special -pie- prefixed background property (bear in mind that CSS3PIE doesn’t add support for background-image, just the shorthand). Look at the following example from the Monty Python blog (I’ve removed all the less interesting and prefixed properties for brevity):

aside article {
    ...
background: repeating-linear-gradient(45deg, rgba(0,0,0,0.1) 1px, rgba(0,0,0,0.05) 2px, rgba(0,0,0,0.1) 3px, rgba(0,0,0,0) 4px, rgba(0,0,0,0) 5px);
background-color: rgba(255,255,255,0.4);
border-radius: 4px;
box-shadow: 2px 2px 10px black;
}

The result is a rather nice container with a shadow, rounded corners, and a textured repeating gradient pattern (Figure 4.28).

Figure 4.28

Figure 4.28 An attractive bling box.

To add IE support after you’ve placed the PIE.htc file, you can add the following two lines, which include a far simpler gradient without an alpha channel that is still in keeping with the color scheme (Figure 4.29):

-pie-background: linear-gradient(45deg, #6988af, #a6b9cf);
behavior: url(/cmills/arthur/script/PIE.htc);
Figure 4.29

Figure 4.29 A pleasing alternative set of styling provided for older versions of IE.

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