In addition to setting the background color with
background-color: COLOR;, where COLOR is the color of the background, we can also set a background image with
where the URL is the path/name of the image file. We use the image file path/name without quotes.
We can cause the browser to repeat an image and we can control the direction of the repeat with
repeat-x (to repeat horizontally) or
repeat-y (to repeat vertically) with the following CSS rule.
We can set the initial position of the image using the
background-position attribute. The value can be two values with a space in between; the first being the distance from the left and the second being the distance from the top. Or, we can specify just one value to move it to the right and make it centered vertically. For example:
|CSS Rule||Placement of Image|
||10% of the width to the right, and 20% of the length down from the top left corner of the element|
||25 pixels to the right of the element's left border, and centers it vertically|
||lower right corner of element - can use left, center or right for horizontal placement and top, center or bottom for vertical placement|
By default, the background scrolls along with the document. We can change this behavior to cause the background to remain fixed as the page scrolls by setting the
background-attachment value to
fixed as in the following code.
background-attachment: fixed; (Example)
Fixed backgrounds create a watermark effect, in which a subtle, often translucent graphic is displayed behind elements to mimic the watermarks found on some specialized stationery.
Let's take a look at a few style properties for background images.
background-size: width height;
Width and height can be specified in any of the CSS units of length or as a percentage of the element's width and height, or as keywords
auto, cover or
contain. Let's look at some examples.
background-size: 300px 200px;
Sets the size of the background image to 300 pixels wide by 200 pixels tall.
background-size: auto 200px;
Sets the height of the image to 200 pixels and automatically sets the width to maintain the aspect ratio of the image. In other words, it will not stretch the image. It will remain in proportion.
background-size: cover; (Example)
Will cause the image to scale until it covers the entire element, but part of the image is cropped.
Note: Browser support is not 100% - especially IE!
background-size: contain; (Example)
Makes the image scaled so the entire image is contained within the element, but part of the image is uncovered. Note: Browser support is not 100% - especially IE!
In the box model, every element contains a content box, a padding box, and a border box. So the value for BOX can be
Again, the value for BOX can be
padding-box (default), or
We can combine the background properties in to the shorthand property.
background: color url(URL) attachment position repeat;