Background images part 1 - A Smarter Way To Learn HTML & CSS (2015)

A Smarter Way To Learn HTML & CSS(2015)

76
Background images part 1

In previous chapters you learned how to underlay an element with a solid color using background-color. You can also underlay an element with an image. This is an example.

div#main {
background-image: url("images/field-of-poppies.jgp");
}

The div with an id of “main” will be underlaid with the image whose URL is shown inside the parentheses and quotation marks.

You can put a background image behind any element. It’s common to underlay the whole page with an image.

body {
background-image: url("images/gray-gradient.png");}

The entire page will be underlaid with the image whose URL is “images/gray-gradient.png”. In the example above, the image, which must be sized to fit the whole page, will be a large one, and so will take some time to load. If your background image is nothing but a repeating pattern, you can make it load faster by specifying a small slice for the image and asking the browser to repeat it.

You can cut this image down to a 1-pixel-wide slice that has the same height, and write this CSS:

body {
background-image: url("images/gray-gradient-slice.png");
background-repeat: repeat-x;
}

The slice will be tiled all across the width of the page (the x-axis), creating the same effect as the big image, but using a fast-loading small image.

Suppose you have a gradient fading from left-to-right rather than top-to-bottom. Then you would take a 1-pixel-high horizontal slice and tile it from top to bottom (the y-axis).

body {
background-image: url("images/gray-gradient-slice.png");
background-repeat: repeat-y;
}

If you have a background image that you want to repeat both horizonally and vertically, omit the background-repeat: specification.

body {
background-image: url("images/gray-gradient-slice.png");
background-repeat: repeat-x;
}

The browser will automatically tile the image in both directions to fill the page.

In your CSS file, find the div that’s 20% wide. Tile the following image across the width of the div: http://www.asmarterwaytolearn.com/gray-gradient-slice.png. Save the file. Display the page. Check out the div.

Sample CSS code is at:
http://asmarterwaytolearn.com/htmlcss/practice-76-1.html.

Find the interactive coding exercises for this chapter at:
http://www.ASmarterWayToLearn.com/htmlcss/76.html