6a. Backgrounds in CSS

Background property helps to set the background style, property, and effects of the element.

Shorthands

All the background properties would look something like this in a single line.

selector{
    background: [background-color] [background-attachment] [background-image] [background-repeat] [background-position];
}

background_shorthand.png
Example:-

div{
    background: purple fixed url("./harrybhai.png") no-repeat right top;
}
  • There are various background properties, such as:-

Background color

The background color property sets the background colour of HTML tags such as div, section, p, etc.

Syntax:

selector{
      background-color: color;
}

Note: Color can be hex, rdb, hsl, etc. Follow 4. Color is CSS Tutorial

Example:-

<html>
<head>
    <style>
        div{
            background-color: yellow;
        }
        h1{
            background-color: [[FF0000]];
        }
        p{
            background-color: orange;
        }
        span{
            background-color: purple;
        }
    </style>
</head>
<body>
    <div>
        <h1>CodeWithHarry</h1>
        <p>Developer and founder of <span>CodeWithHarry.com</span></p>
    </div>
</body>
</html>

Output:-
background_color.png


Background Image

The Background Image property sets an image as a background by providing the image URL within the url() function.

Syntax:-:

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

Example:-

<style>
        div{
            background-image: url('harrybhai.png');
        }
</style>

Output:-
background_image.png

The image is repeated many times because CSS repeats the image on both the x and y axes, to avoid leaving empty spaces due to the image dimensions.
To solve this issue, use the background property repeat.


Background repeat

Background repeat helps to control how the image will repeat.

Syntax:-

selector{
   background-repeat: repeat-x || repeat-y || repeat || no-repeat;  /* || means or */
}
  • background-repeat can be set to repeat, no-repeat, repeat-x (horizontal), or repeat-y (vertical) or separately.

repeat

The background image is repeated in both the x and y directions. This is the default.

Syntax:-

selector{
   background-repeat: repeat;
}

Example:-
background_repeat_repeat.png

no-repeat

The background image is not repeated in any direction. Only one image will be on the screen.

Syntax:-

selector{
   background-repeat: no-repeat;
}

Example:-