Background in CSS

CSS instructions are, by agreement, written in a line after line basis, separating each instruction with a semicolon, and each set of instructions with brackets. On this page, you are going to learn how to write CSS instructions that affect the background of a page.

Background instructions include:


With background-color you specify the background colour of a specific tag; with background-image, you specify the name of the file that will serve as background for a web page; with background-position, you specify the horizontal and vertical position in which the background-image will be; with background-attachment you will specify whether the background image will scroll with the rest of the page or whether it will remain fixed in a given place; and with repeat, you will specify whether the browser should repeat the image or not. Last, with background, you will set all these conditions with one single line.

CSS background options

background-color accepts colour names like silver or maroon, rgb values such as rgb(0,0,0) or hexadecimal values like #fff. For Heptagrama, for example, we chose this value:

background-color: #682468;

background-image accepts the name of a file only. You need to write this inside parenthesis, like this:

background-image: url(image.jpg);

background-attachment usually considers fixed or scroll as values:

background-attachment: fixed;

repeat accepts four alternatives: repeat will tile the background-image indefinitely; repeat-x will repeat the image in an horizontal only; repeat-y will repeat the image in a vertical line only; and no-repeat will only show it once.

repeat: no-repeat;

background-position usually work better when you use percentages or the words top, bottom, left, right. You can use other measures, though:

background-position: bottom right;


So, if, for example, you would like to have a white background with your logo on the bottom right corner of your web page, you will need to specify this:

body {
background-color: white;
background-image: url(yourlogo.gif);
background-attachment: fixed;
repeat: no-repeat;
background-position: bottom right;

Likewise, if you want all the emphasis you make on the web page to have a light yellow background, you can easily do this:

em {
background-color: #ffffcc;

As you see, you can use only the CSS instructions you need.


By agreement, to avoid writing the five instructions we wrote above, you can abbreviate the set of background instructions using background, like this:

background: white url(yourlogo.gif) fixed no-repeat bottom right;

However, you need to know that if you use the contraction, you need to specify all the elements and in the same order: background-color, background-image, background-attachment, repeat, background-position; else you run the risk of not seeing it working properly.

Knowledge + Computers