SITERAW

Color and background

Let's continue our guide of the essential CSS properties.

In this chapter we are mainly going to talk about the properties related to colors and backgrounds.

Yes, plural.

As you will see, there are many different ways to adjust the color of an element in CSS.

In addition to that we're also going to cover how to change the color of the background, create gradients, adjust transparency and more.

CSS is not done impressing you.

Text color

Since we have to start somewhere, let's begin with the concept of colors.

We briefly saw the CSS property color in the first chapter of this second part, Setting up CSS.

It's usage is quite intuitive, you simply indicate the name of the color you want to apply as a value.

p { color: red; }

This code will turn all your paragraphs red.

But that's far from the only way you can use the color property.

We'll have a look at the different ways of specifying a color, there are many.

Colors in CSS
Colors in CSS

Colors by name

One easy and convenient way to specify a color is simply by entering its name or keyword.

For example.

h1 { color: magenta; }

p { color: olive; }

strong { color: red; }

This code is rather self-explanatory, it turns your titles magenta, your paragraphs olive (a yellowish shade of green) and your emphasizes red.

The result is shown below.

A demo of CSS colors
A demo of CSS colors

That's the method we've used until now but it comes with its drawbacks: a limited number of colors to choose from.

It's fine as long as we're working with a rudimentary pallet of colors, but it's not doing CSS justice to restrict our choices to only the colors which dispose of a name.

CSS color pallet
CSS color pallet

What if we want a shade of red somewhere between Crimson and FireBrick?

Luckily, there are other methods we can use to indicate a color with more accuracy.

Colors by hexadecimal

Most monitors can display over 16 million colors and CSS allows you to use any tone you want on your web page.

Obviously, for practical reasons, not every shade of red has an established name.

We need another way of specifying the color we want.

One of such ways is the hexadecimal notation.

This is the most commonly used format for indicating colors on the web.

Here is a demonstration of this nomenclature.

h1 { color: #FF0000; }

This code will make your titles red.

I don't get it! Wouldn't it be easier to just write "red" like we used to do?

That remark is true for this example, but hexadecimal enables you to specify colors in a much less restrictive way than by typing their names.

If you've never seen hexadecimal employed before, it's just a different numeral system from what you're used to (decimal).

The numbers are exactly the same as decimals, but instead of having digits go from 0 to 9 (decimal) they go from 0 to 15 (hexadecimal).

You've probably heard of at least one other numeral system before: binary, which goes from 0 to 1.

The base (or radix, for mathematicians) is therefore 16 instead of 10.

Since we don't have symbols for digits higher than 9, we had to borrow them from our Latin alphabet.

The numbers "ten" to "fifteen" become single-digit numbers represented by A to F ("ten" is A, "eleven" is B... "fifteen" is F).

More colors with hexadecimal
More colors with hexadecimal

The hexadecimal notation is sometimes and more accurately called hex triplet as it consists of three distinct sections.

In total you have 2563 = 166 = 224 = 16,777,216 colors to choose from.

The number in our example is #FF0000.

Hex triplets always start with a hash character (#) in CSS and most other computing applications.

After that we have six characters from the hexadecimal numeral system.

They work by pairs and, from left to right, indicate the quantities of red, green and blue, also called the RGB (Red-Green-Blue) value of our color in the following way.

  • Red: 00 (no red) to FF (max red)
  • Green: 00 (no green) to FF (max green)
  • Blue: 00 (no blue) to FF (max blue)

As you will have guessed, #000000 (no color) is black and #FFFFFF (max of everything) is white.

The hexadecimal color notation
The hexadecimal color notation

The color we used in our example was #FF0000. Maximum red, no green, no blue.

The final result is obviously red.

But what if I want a light blue color, something halfway between navy blue and cyan?

From the top of my head I could try #00BAFF.

No red, about 75% of green and maximum blue.

Here is the result as shown in Photoshop.

Photoshop hexadecimal color wheel
Photoshop hexadecimal color wheel

Drawing software programs like Photoshop are convenient in that they allow you to pick the color you want directly from a color wheel and simply copy and paste the result in your CSS file.

If you don't have such software you can also try Adobe's Color Picker directly from their website.

I used uppercase letters in my hexadecimal colors simply because they are easier to distinguish than lowercase ones. You can use whichever form you want, there are no rules or conventions. #FFFFFF is the exact same as #ffffff.

The shorthand hexadecimal form

There exists an abbreviated form of hexadecimal colors called the shorthand notation.

This method shortens the six digits of hexadecimal color codes into three characters.

It only works if every two digits in a pair are identical.

For example, #FF77AA becomes #F7A and #33CCEE can be written as #3CE.

For this method to work, every two digits that compose a pair must be the same. As such, #FF8811 can be shortened but #F7C63D cannot.

Colors by RGB value

The second method used to indicate a color is the RGB scale.

To be fair, it's not so much a different method as an alternative notation of the hexadecimal form.

Both use the RGB (Red-Green-Blue) color model, although this time we're not bothering with hexadecimals.

The RGB method just uses regular decimals to designate a specific color.

Here is an example of its syntax.

h1 { color: rgb(255, 0, 0); }

This will turn your titles red.

The number 255 is simply the decimal form of FF.

We can write red, #FF0000, #F00 or rgb(255, 0, 0) for the same effect.

Similarly, any hex triplet can easily be converted to RGB with simple math.

The color #FFBA00 becomes rgb(0, 186, 255). As B (11) x 16 + A (10) = 186.

Try it yourself.

p { color: #00BAFF; }

em { color: rgb(0, 186, 255); }

Different syntax, same color.

But what's the point of the RGB notation if it's the same as the hexadecimal form?

It's a matter of preference.

The hex format is often favored as it is easily readable and more compact.

It's always good to know both, and there is a particular instance where it's more convenient to use the RGB representation.

We'll learn more about this case a bit further on in this chapter.

In addition, you can also find the RGB value of any color simply by using a graphics editor such as Photoshop.

The RGB scale in Photoshop
The RGB scale in Photoshop

Background color

We saw how to change the text color on our web page in CSS.

But how do we modify the background color?

To indicate a background color you just use the background-color property.

It works in the exact same way as color, meaning you can specify a color by typing its name, its RGB value or by using the hexadecimal notation.

Let's try it out.

body
{
    background-color: black;
    color: white;
}

Which should give you the following result.

A darker background with CSS
A darker background with CSS

There is nothing very complicated about this code, it simply turns the background black and the text white.

But why are the title and text white as well? The color property is only changed on the <body> tag!

Good point.

This is called inheritance and is a main feature of CSS.

Inheritance is the process by which properties are passed from parent to child elements.

In the case of nested tags, once a style is applied to an element, every other element within it will inherit the same style.

In our example, since the header <h1> and the paragraphs <p> are inside the body tag <body>, they are both rendered with the same properties.

If you want to apply a style to every element in your web page as in our demonstration, you can apply it to either the root <html> or the <body> tag. It's a matter of preference.
So from now on every text I write on my web page will be white?

Not necessarily.

If you apply a new style to one of the child elements, the new properties will take precedence over the inherited style.

For the sake of demonstration let's add a few properties to our example.

body
{
    background-color: black;
    color: white;
}

h1, strong
{
    text-decoration: underline;
    color: orangered;
}

Which gives us.

CSS inheritance
CSS inheritance

The most specific definition takes precedence, so the <strong> and <h1> tags will be orange while any other text remains white.

This is true for every CSS property, not just for text and background colors.

CSS3 gradients

Alright... changing the background color was pretty cool.

But what about adding a gradient?

Prior to CSS3 you had to use images to get a transition between two or more colors, an effect you can now attain simply with the background-image property.

Linear gradients

A linear or axial color gradient is the most common type of gradient you will come across.

As it name suggests it provides a transition between two or more colors through a linear axis.

Here is the basic CSS blueprint for a background linear gradient.

background-image: linear-gradient(direction, color1, color2);

The default direction is from top to bottom.

For example.

background-image: linear-gradient(yellow, orange);

Which will give you the following result.

CSS linear gradient
CSS linear gradient

As mentioned above, linear gradients are by default vertical and from top to bottom.

If you want to change that, you can very easily add a direction value either by typing it out or by providing an angle in standard geometrical degrees.

background-image: linear-gradient(to right, deepskyblue, lightskyblue);

background-image: linear-gradient(90deg, deepskyblue, lightskyblue);

These two lines render the exact same gradient, shown below.

CSS horizontal gradient
CSS horizontal gradient

You can also indicate a diagonal direction as follows.

background-image: linear-gradient(to bottom right, orange, yellow);

Which will naturally give you a diagonal gradient.

CSS diagonal gradient
CSS diagonal gradient

That covers pretty much every type of dual-colored linear gradient you will come across.

But what if you want to have more than two colors?

All you need to do is add the supplementary colors at the end of the code.

background-image: linear-gradient(skyblue, yellow, red);

This will give you a top to bottom (default as unspecified) three color linear gradient.

The result is shown below.

CSS three color gradient
CSS three color gradient

You can of course use as many colors as you want and modify the direction of the gradient as we've seen previously.

Radial gradients

A radial gradient is very similar to a linear gradient as they both produce a dynamic transition between two or more colors.

In simple terms, a radial gradient is an ellipse or a circle that possesses one color at the edge and another at the center. Colors are calculated by linear interpolation based on distance from the center.

The syntax is very close to that of the linear gradient as the same background-image property is used.

background-image: radial-gradient(shape, color1, color2);

The default shape is the ellipse.

The first color is the color at the center and the last color is the one closest to the edges.

Let's try it out.

background-image: radial-gradient(yellow, orangered);

This code should give you the following result.

CSS radial gradient
CSS radial gradient

As I said, the default shape is an ellipse.

But you can also make it a circle if you want.

The difference between the ellipse and the circle is that the latter's center is equidistant from every point.

This means that for a given circle, the radius will always be the same and the eccentricity will be 0.

Here is how to create a circular radial gradient in CSS.

background-image: radial-gradient(circle, yellow, orangered);

This covers everything you need to know about gradients in CSS.

Background image

Just as we can change the background color of a page, or an element thereof, we can also add a background image.

You can either add a background image to your entire page or to a specific element, such as a title or a text link.

We will also see how we can repeat the background in a mosaic pattern or have it "follow" the user as he scrolls down the page.

Adding a background image

Unsurprisingly, the CSS property you need to apply a background image is no other than background-image.

We already saw this property when dealing with gradients and its use with images is similar enough.

The only real difference is in the value of this property.

Instead of being the CSS function linear-gradient or radial-gradient, we'll be using the url function with the path to the image you want as a background.

For example.

body { background-image: url("siteraw.png"); }

Remember that for this code to work, the image siteraw.png must be in the same folder as your CSS file.

This code will give you something close to the figure shown below.

CSS background image
CSS background image

The background image doesn't have to be in PNG, it could also be a JPG or GIF image as we learned in our Inserting images chapter.

A common mistake is to write the path to the image relative to the .html file. If your image doesn't load, make sure that the path is relative to the .css file. In our example, since the .html and .css files are in the same folder the image path is identical in both cases.

Background image properties

The background-image property is by itself very versatile: you can use it for both gradients and background images.

But there are also several other CSS features that can supplement it and allow you to modify the behavior of your background image even further.

Here are a few of these features.

Background attachment

The first property we'll learn about is background-attachment.

As its name suggests, it is used to "attach" the background to the page or to the element to which it is applied.

Here are the two values it can take:

  • scroll : the background will scroll with the rest of the page (default)
  • fixed : the background will remain fixed with regard to the viewport

Let's try it out with our example.

body
{
    background-image: url("siteraw.png");
    background-attachment: fixed;
}

To see the effect you need a sufficient amount of content for the vertical scrollbars to appear on your browser.

If you don't have them, try adding some text or reducing the window size.

Background repeat

By default, if the background image is smaller than the viewport, it will be repeated in a mosaic pattern either horizontally, vertically or both depending on the size of the image and the user's screen resolution.

For instance.

CSS background repeat
CSS background repeat

This behavior can be changed with the background-repeat property.

Here are the values it can take.

  • repeat : the image will be repeated both horizontally and vertically (default)
  • repeat-x : the image will be repeated horizontally
  • repeat-y : the image will be repeated vertically
  • no-repeat : the background won't be repeated

Example of use.

body
{
    background-image: url("siteraw.png");
    background-repeat: no-repeat;
}

Background size

By default, the background will take the exact size of your image.

But you can also specify a value with the background-size property.

You can either define an identical value for both the height and width, or list them separately starting with the width.

background-size: 50%;
/* Both the height and width will be halved from their original values */

background-size: 300px 450px;
/* Width: 300px, Height: 450px */

To indicate a length value, you can use inches, pixels, percentages or any other unit we saw in the Text formatting chapter.

If you want either the height or the width to scale automatically with the image size, simply use the auto value.

This is the default value of the background-size property.

background-size: auto auto;

Background position

The last property we'll cover concerns the position of the background image.

You can specify how the background image should be positioned with background-position.

This property is only interesting if you set background-repeat to no-repeat (a non-repeating background).

Here are the values it can take.

  • top : at the top
  • bottom : at the bottom
  • left : to the left
  • right : to the right
  • center : centered

These values can be combined.

To align your background image with the top right corner, you would write.

background-position: top right;

Instead of the predefined values listed above, you can also specify a pair of lengths to represent the position of the background image relative to the top left corner of the page or of the element to which it is applied, starting from the left.

background-position: 35px 50px;

The code shown above will position your background image to the top left, with a 35 pixel offset from the left and a 50 pixel offset from the top.

The background super-property

We discovered quite a few ways to modify our background, whether by filling it with a color, adding an image or even tempering with its size, attachment and position.

The only issue is that all this can get quite inconvenient to write down each time we decide to adjust our background.

Consider the following code.

body
{
    background-color: #f00; /* In case the image doesn't load */
    background-image: url("siteraw.png"); /* Our background image */
    background-repeat: no-repeat; /* The background won't be repeated */
    background-attachment: fixed; /* The background will remain fixed */
    background-position: top right; /* The background will be aligned to the top right */
}

Rather lengthy.

But what if I told you there was a way to shorten everything I just wrote into one single CSS property?

It's entirely feasible with the background super-property.

Shorthand properties or "super-properties" are used to minimize syntax by combining the values of several related properties.

Here is how it works.

background: <color> <image> <repeat> <attachment> <position>;

The order in which the values are placed is important.

Going back to our example, using the background super-property transforms our code into the following.

background: #f00 url("siteraw.png") no-repeat fixed top right;

You don't have to use every property. Those left unspecified will simply take their default value.

For example, if you only wanted a background color and a background image you would write.

background: #f00 url("siteraw.png");

If for any reason the background image can't be loaded, the background color will be shown instead. This is a common CSS practice.

Shorthand properties or super-properties are very useful for condensing and simplifying your CSS code.

For now we only learned about background, but we will see many others in this tutorial.

Transparency

So now that we learned how to colorize our text, how to change background colors and even how to insert a background image... what could there possibly be left in this chapter?

If you guessed transparency, that only proves you know how to read titles. Congratulations.

There are two ways to handle transparency in CSS: the opacity method and the RGBa notation.

While they are very similar in theory, they both have distinct practical uses.

The opacity method

The opacity method makes use of the opacity property.

Its value is a decimal between 0 and 1:

  • a value of 1 will make the element completely opaque (default)
  • a value of 0 will make the element completely transparent

Anything in between will be adjusted accordingly.

As such, an opacity of 0.7 will produce a 70% opaque (and 30% transparent) element.

Here is how it can be used.

p { opacity: 0.7; }

For a more visually revealing example have a look at the following code.

body
{
    background: #000;
    color: #fff;
}

p
{
    background: orangered;
    opacity: 0.5;
}

And the result.

Opacity and transparency
Opacity and transparency

The <body> element has a black background and white text.

The opacity decimal isn't specified so it will take the default, 100% opaque value.

On the other hand, we set the opacity for the <p> tag to 50%.

You can see the result above: the paragraphs are half transparent.

But why is the text transparent? What if I only want the background to blend in with the rest of the page?

Good point.

Applying the opacity property to an item will affect every element contained within the item including text, images and even other blocks of content.

If you want only the background color to be transparent you should use the RGBa notation that we're going to find out about.

The RGBa notation

At the beginning of this chapter, when we were introducing the different methods to specify colors, I stated that the hex format was usually preferred except for one case where the RGB notation was more convenient.

This is what I was talking about: the RGBa notation.

It's the same as the RGB notation with an additional setting called alpha channel, which handles transparency.

This fourth component controls the level of transparency in the same way as the opacity property we saw above: a value of 1 will make the color opaque, a value of 0 will make it completely transparent (invisible).

Let's give it a try.

p
{
    background-color: rgb(255, 0, 0);
    /* A red background */

    background-color: rgba(255, 0, 0, 0.5);
    /* A semi-transparent red */
}

Unlike with the opacity, only the background color will be affected by the transparency levels.

This concludes the chapter on colors and backgrounds.