CSS Backgrounds

CSS background property is used to add the background effects on HTML element. There are 5 CSS background properties.

  1. background-color
  2. background-image
  3. background-repeat
  4. background-attachment
  5. background-position
  6. background

CSS background-color :

The background-color property specifies the background color of an element.

You can set the background color as below.

<style>
body {
  background-color: #CCCCCC;
}
</style>

You can set the background color for any HTML elements as below.

<style>
h1{
  background-color: #000000;
}

h2{
  background-color: #FF00FF;
}

table{
  background-color: #003366;
}

p{
  background-color: #CC0066;
}
</style>

 

CSS background-image :

The background-image property is used to set an image as a background of an HTML element. By default, the image is repeated so it covers the entire element.

Example :

<style>
h1{
  background-image: url("images/h1.jpg");
}
</style>

CSS background-repeat :

By default, the background-image property repeats the background image horizontally and vertically. Some images are repeated only horizontally or vertically.

Example :

The below image is repeated horizontally only in background.

<style>
h2{
  background-image: url("images/h2_bg.jpg");
  background-repeat: repeat-x;
}

</style>

 

You can repeat image vertically using background-repeat:repeat-y;

CSS background-attachment:

The background-attachment property specifies whether the background image should scroll or be fixed. If you set fixed the background image then the image will not move during scrolling in the browser.

Example :

<style>
h2{
  background-image: url("images/h2_bg.jpg");
  background-repeat: repeat-x;
 
background-attachment: fixed;
}

</style>

CSS background-position :

The background-position property is used to define the initial position of the background image. By default, the background image is placed on the top-left of the webpage.

Example :

<style>
p{
  background-image: url("images/pbg.jpg");
  background-repeat: repeat-x;
  background-attachment: fixed;
  background-position: left;  
}
</style>

CSS Background Shorthand :

To shorten the code, it is also possible to specify all the background properties in one single property. This is called a shorthand property.

<style>
body {
  background-color: #FF0000;
  background-image: url("images/bg.jpg");
  background-repeat: no-repeat;
  background-position: left top;
}
</style>

You can use the shorthand property background for above as below.
<style>
body {
  background: #FF0000 url("images/bg.jpg") no-repeat left top;
}
</style>

 

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

81645