Same colored pixels aren't always exciting - sometimes those forming an image may be the best deal. What this simply means is that background images are sometimes better off than having a plain background color.
In this chapter we will go over how to add background images using CSS and then go over its related concepts in the coming chapters.
Adding a background image
The background-image
property is used to add a given number of background-images to an element.
The url
function is used to specify the path/url to the image.
p {
background-image: url("back.png");
}
The string in url()
can be either an absolute or a relative URL.
In absolute URLs we need to specify the domain name of the location from where the image file needs to be fetched. The following are some examples of absolute URLs:
http://www.example.com/images/back.png
https://images.example.com/back.png
In relative URLs we don't need to specify the domain name of the location. The path can be root-relative or traversal. The following are some examples of relative URLs:
/images/back.png
../images/back.png
The first path is relative to the root of the website whereas the second one traverses up one directory from its current location and then from there starts to parse the rest of the path.
Image file types
CSS supports nearly all the commonly used image file types including png
, jpg
, gif
and svg
. There isn't that much to discuss on file types except for knowing what is supported and what isn't.
Gradients
Uptil now we've only applied actual images to the backgrounds of elements, using the url function, but now we will look over another class of backgrounds known as gradients.
Basically gradients are blends of colors going from one hue to another one.
We will discover gradients in detail in the CSS Gradients chapter so for now just consider the example below. There is quite a lot in gradients, which can't be completely discussed in this chapter therefore we've anchored it in a coming one.
We have two types of gradients - firsly linear ones:
p {
background-image: linear-gradient(to right, white, #ccc);
}
A paragraph with linear gradient
And secondly radial ones:
p {
background-image: radial-gradient(white, #ccc);
}
A paragraph with radial gradient
Gradients are a powerful tool in CSS and knowing how to work with them is essential as a designer.