CSS Backgrounds

Keywords

css, colors, css colors, css backgrounds, background color, dataidea, data science, web development, website

Photo by DATAIDEA

Backgrounds

Element’s backgrounds can be filled with a color or image, clipped and/or resized and otherwise be modified.

CSS background properties:

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

Background Color

We can specify a background color for an element using the background-color property

The value can be any valid CSS Color

Changing the background color of whole page:

body {
    background-color: gold;
}

Changing the background color of elements:

h1 {
    background-color: yellow;
}

p {
    background-color: pink;
}

div {
    background-color: gray;
    width: 200px;
    height: 200px;
}

Background Image

The background-image property sets one or more images as a background of an element.

The format of its value should be url("image.jpg"). Single quotes or no quotes work eg url('image.jpg') and url(image.jpg)

The text contained in the quotes are file paths.

Note!

Don’t use any background color or image that will disturb the text on your web page. Always keep everything readable

Background Image Repeat

CSS automatically repeats background images horizontally and vertically.

To only repeat the background image horizontally or vertically, we can use the background-repeat property.

Horizontally-repeating background image

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

Vertically-repeating background image

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

Background Image no-repeat

The no-repeat value of the background-repeat property stops a background image from repeating.

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

Background Shorthand Property

We can specify all CSS background properties in one single property using its shorthand property

The background property is a shorthand for the following CSS properties

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

Example:

A CSS Background with the following properties…

body {
    background-color: red;
    background-image: url("image.jpg");
    background-repeat: no-repeat;
}

… can be shortened to:

body{
    background: red url("image.jpg") no-repeat
}

To be among the first to hear about future updates of the course materials, simply enter your email below, follow us on (formally Twitter), or subscribe to our YouTube channel.

Back to top