This website may use cookies. More info. That's Fine x
Welcome Login

Css: background


Css

The background shorthand property sets all the background properties in one declaration.

 

The properties that can be set, are (in order):

background-color, background-image, background-repeat, background-attachment, and background-position.

 

The background properties are:

  • background
  • background-color
  • background-image
  • background-repeat
  • background-attachment
  • background-position

 

Eg: to specify all the background properties in one declaration

body {
    background: #00ff00 url('smiley.gif') no-repeat fixed center;
}

 

 

 

background-color property:

background-color property pecifies the background color to be used.

Eg:

body { background-color: yellow; } 

h1 { background-color: #00ff00; }

p { background-color: rgb(255,0,255); }

 

 

 

background-image property:

background-image property specifies the background image to be used.

Eg:

<!DOCTYPE html>
<html>
<head>
    <style>
    body 
    {
        background-image:url('paper.gif');
        background-color:#cccccc;
    }
</style>
</head>

<body>
    <h1>Hello World!</h1>
</body>
</html>

 

Outputs:

css-backgroundimage1

 

 

 

background-repeat property:

Specifies how to repeat the background image.

Eg:

body {
    background-image: url('paper.gif');
    background-repeat: repeat; (both x and y dir) | repeat-x | repeat-y | no-repeat
}

 

 

 

background-attachment property:

Specifies whether a background image is fixed or scrolls with the rest of the page.

Eg:

body
{
    background-image:url('smiley.gif');
    background-repeat:no-repeat;
    background-attachment:fixed;
}

 

 

 

background-position property:

Specifies the position of the background image. See background-position for possible values.

If you would like to define where exactly an image appears within an HTML element,  use CSS's background-position. Take note that there are three different ways of defining position: length, percentages, and keywords. Recommend using lengths - specifically, pixels.

Eg:

body
{
    background-image:url('smiley.gif');
    background-repeat:no-repeat;
    background-attachment:fixed;
    background-position:center;
}

 

Eg2:

p {
    background-image: url(smallPic.jpg);
    background-position: 20px 10px;
}

h4 {
    background-image: url(smallPic.jpg);
    background-position: 30% 30%;
}

ol {
    background-image: url(smallPic.jpg);
    background-position: top center;
}

 

 

 

Gradient background:

Use background-image and background-repeat to create a gradient background.

Eg:

p {
    background-image: url(/images/bg-gradient.gif);
    background-repeat: repeat-x;
}

Created on: Thursday, March 24, 2011 by Andrew Sin