CSS

background-image: url(”image.png”);

As usual, if you use a PNG image, the browser will consider the transparency settings of the image. So if you have an icon without a background, for example, the image will sit nicely over any colour you have behind it without any issues. This can be extremely powerful. If you were to apply a background-colour property to an element and also a background-image, the background image would appear over the top of the background colour, allowing you to ‘layer’ your background as you wish. This is an extremely powerful technique for creating unique backgrounds. The syntax for this rule is slightly different to anything we have seen before. We have a hyphenated property ‘background-image’ and the value contains a keyword ‘url’, brackets and speech marks. This might seem bizarre at first as it is so different from how we write other rules, but it’s actually fairly simple. The biggest consideration here is how to format your URL. As with HTML you can specify your URL in either absolute or relative terms. Remember, if you use a relative path, this will search for your image relative to the location of your CSS file, not your HTML webpage that you attach the CSS file to inside the <head>tag.

Background-repeat

When using a background image, if the image is smaller than the size of the element it is used on, the image will repeat to cover the entire size of the element, as shown in Figure 5.1.

5.1 image

This is where the background-repeat property comes into use. We are able to apply any of the following values to the property in order to control the repeating nature of the background image.

no-repeat

The background image will not repeat at all, regardless of the size of either the image or the element (see Figure 5.2).

5.2 image

repeat-x

The background image will only repeat horizontally, but will still repeat until the full width of the div is covered with the image (see Figure 5.3).

5.3 image

repeat-y

The background image will only repeat vertically, but will still repeat until the full height of the div is covered with the image (Figure 5.4).

5.4 image

Background-position

The background-position property does pretty much exactly what you would expect it to do – positions the background image as per your specified value.

Generally you would provide two values for this property – the horizontal and vertical values – to define where you want the image to be positioned inside your element. A classic example of this would be as follows: