Previous Next

CSS Backgrounds

The CSS background property is employed to specify the element's background style and effects.

There are a number of background properties, such as:

Background color

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

Syntax:

selector {
    background-color: color;
}

Example:

HTML

<!DOCTYPE html>
<html>

<head>
   <title> CSS Backgrounds </title>
</head>

<body>
   <h1> CSS Background Color </h1>
   <p> This is an example of CSS background color. </p>
</body>
</html>

CSS

h1 {
    background-color: aqua;
}

p {
    background-color: aquamarine;
}

Output

Background color

Background Image

The background-image property specifies the image that will be used as the element's background.

Syntax:

selector {
   background-image: url('image-url');
}

Example:

HTML

<!DOCTYPE html>
<html>

<head>
    <title> CSS Backgrounds </title>
</head>

<body>
   <h1> Background Image </h1>
   <p> This page has an image as its background. </p>
</body>
</html>

CSS

body {
  background-image: url("random.png");
}

Output

Background image

Background repeat

The background-repeat property specifies how background images should be repeated.

Syntax:

selector {
    background-repeat: repeat | repeat-x | repeat-y | no-repeat;
}

repeat

The background image is repeated both horizontally and vertically. This is the default behavior.

Syntax:

selector {
    background-repeat: repeat;
}

Example:

HTML

<!DOCTYPE html>
<html>

<head>
    <title> CSS Backgrounds </title>
</head>

<body>
   <h1> Background repeat </h1>
   <p> This background image is repeated both horizontally and vertically. </p>
</body>
</html>

CSS

body {
  background-image: url("random.png");
  background-repeat: repeat;
}

Output

Background repeat

repeat-x

The repeat-x lets the background image repeat horizontally but not vertically.

Syntax:

selector {
    background-repeat: repeat-x;
}

Example:

HTML

<!DOCTYPE html>
<html>

<head>
    <title> CSS Backgrounds </title>
</head>

<body>
   <h1> Background repeat-x </h1>
   <p> This background image is repeated only horizontally! </p>
</body>
</html>

CSS

body {
  background-image: url("random.png");
  background-repeat: repeat-x;
}

Output

repeat-x

repeat-y

The repeat-y lets the background image repeat vertically but not horizontally.

Syntax:

selector {
    background-repeat: repeat-y;
}

Example:

HTML

<!DOCTYPE html>
<html>

<head>
    <title> CSS Backgrounds </title>
</head>

<body>
   <h1> Background repeat-y </h1>
   <p> This background image is repeated only vertically! </p>
</body>
</html>

CSS

body {
  background-image: url("random.png");
  background-repeat: repeat-y;
}

Output

repeat-y
Previous Next