CSS Backgrounds
Tags: beginners, css
Published: 2019-11-12 21:59:30

---
title: CSS Backgrounds
published: true
description: A quick introduction to CSS backgrounds
tags: beginners, css
series: FrontEnd Development Zero to Hero
---
Backgrounds in CSS are used to add effects to a web page in the form of colors or images.

Backgrounds can be applied to the whole web page or part of it.

_We will be using the following snippets in this post with slight modifications along the way. Please save the snippets with the `.html` and `.css` extensions respectively and remember that all HTML snippets will be in the `body` tag_.


```html
<div class="parent">
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
</div>
```

```css
div {
  padding: 1.2em;               /* some internal spacing */
  color: #ffffff;               /* the text color. this will be white */
  font-size: 1.2em;             /* the font size equivalent to 19.2px */
  background-color: #1560bd; 	/* a variant of blue */
}
```

_And kindly note that all screenshots are from <b>Firefox 70</b> web browser and its Developer Tools._

<hr>

The following CSS properties are used to add or control a web page background:

* `background-color`
* `background-image`
* `background-repeat`
* `background-attachment`
* `background-position`
* `background`


###__`background-color`__

We used this property at the end of the [last post](https://dev.to/ziizium/css-colors-7ai), this property sets the background color of an element, either a color value or the keyword `transparent`.

Load the HTML file in the browser.

The resulting image in the browser and the _Developer Tools_ indicate the text is accessible. Hooray!

![A white text on a blue background](https://thepracticaldev.s3.amazonaws.com/i/qrocai2due62rzey7zi7.PNG)

###__`background-image`__

The background image of the whole page or part of it can be changed using the `background-image` property.

It is a recommended practice to specify a `background-color` that will be used when the image is unavailable and when the image is available it is rendered on top of the background color.

The `background-image` property can accept two properties:

* A `url()` function which will point to the location of the image
* The keyword `none` when no image is used.

Update your CSS to match the following and save your file.

```css
div {
  /*
   * The url() function accepts the location of the file.
   * This can be a file on your system or on the internet.
   * in this example the image is on my local machine in a folder
   * named img.
   * If your file is on the internet it'll look like
   * url('https://example.com/my_image.jpg')
  */

  background-image: url('img/hd_10.jpg');  /* The bacground image */
  color: #ffffff;				 /* The color of the text */
  padding: 1.2em;				 /* Some padding for internal spacing */
}
```

Load the HTML in the browser. Your output should be similar to the image below.

![A text with a background image](https://thepracticaldev.s3.amazonaws.com/i/bi5z31vfvztp7unfmiam.PNG)

Then what happens if the image fails to load?

Let's break our code by __deleting part of the image extension.__

```css
div {
  /*
   * The image extension has been modified by deleting
   * the 'g' in the extension and we are left with 'jp'.
  */
  background-image: url('img/hd_10.jp'); /* Note the image extension */
  color: #ffffff;
  padding: 1.2em;
}
```

Save your file. Refresh your browser. The text will be unreadable.

![An unreadable text on a web page](https://thepracticaldev.s3.amazonaws.com/i/3qead9x3ianbf7yrhmt6.PNG)

The question now is: _How can we make this text readable when the image fails to load or not available?_

First let's get our image back by modifying our code. Perform the following steps:

* __Add the deleted part__ of the extension
* Save your file and refresh your browser
* Confirm the image loads

We good? The text can be readable if we supply a fallback color that the browser will use when the image is unavailable.

The fallback color we specify must meet the following requirement:

* The color should be similar to the color of the image or part of the page that the text is rendered on

Make sure your code is fixed and the image loads. Now, switch over to your browser, and perform the following steps:

* Use "Inspect Element" on the paragraph text
*  Under the __Rules__ tab click on the _colored circle_ beside the Hexadecimal color code
* Click the _icon_ with the black top, this will enable an inspector like tool
* Hover the tool over the background image of the text, this will show a color code in hexadecimal format
* This will be our fallback color.

![An hexadecimal color for a background image](https://thepracticaldev.s3.amazonaws.com/i/9az4ai9y412t0lwvzhy5.PNG)

Now that we have our fallback color, lets update our CSS with this color:

```css
div {
  /* All other properties remain the same */

  background-color: #213a59;		/* The fallback background color */
}
```

Save your file and refresh your browser. You won't see any changes (yet).

Perform the following steps:

* Break your code by __deleting part of the image extension__ like we did before.
* Save and refresh your browser.

The background color will now take effect when the image fails to load and the result will be the same as if the image was there.

![A text on a blue background](https://thepracticaldev.s3.amazonaws.com/i/hforw3btw18qjqnnaujx.PNG)

Mind you, the background image can also be applied to the whole web page.

###__`background-repeat`__

If a background image is specified, this property specifies whether the image is repeated and how.

This property accepts the following values
* `repeat`    &#x2014; The image is repeated both horizontally and vertically.
* `repeat-x`  &#x2014; The image is repeated horizontally only.
* `repeat-y`  &#x2014; The image is repeated vertically only.
* `no-repeat` &#x2014; The image is not repeated: only one copy of the image is drawn.
*  `inherit`  &#x2014; The repeat direction is inherited from the parent element.

Let's demonstrate some of of these properties. To follow along I'll encourage you to use a small sized image.

The image I'll be using in the code snippets is measured _395 by 463_ which means:

* The width of the image is `395` pixels
* The height of the image is `463` pixels

Given the code snippet below:

```css
body {
  background-image: url('img/hd_11.jpg');
  color: #ffffff;
}
```

Save your file and refresh the browser.

If you followed my recommendation and used a small sized image for the background, the image will tile in the _horizontal_ and _vertical_ direction.

![A background image applied to a web page](https://thepracticaldev.s3.amazonaws.com/i/s8vt7wt4yiun5907daop.PNG)

Now update your `body` declaration with the following:

```css
body {
  /* All other properties remain the same */
  
  background-color: #dddddd;    /* added to see the tiling of the image */
  background-repeat: repeat-x;  /* image will be repeated in the horizontal direction */
}
```

The resulting output in the browser will show the image tiling in the horizontal direction. The grey background image will let you see this.

![A background image tiled in the horizontal direction](https://thepracticaldev.s3.amazonaws.com/i/iqytasfxolyi3rvlxyi5.PNG)

Change the repeat direction to `repeat-y` and save your file.

```css
body {
  /* All other properties remains the same */
  
  background-repeat: repeat-y; /* change to this value */
}
```

The result in the browser:

![A background image tiled vertically](https://thepracticaldev.s3.amazonaws.com/i/lrjd54ya9nkv6e8bb3w2.PNG)

If we use the `no-repeat` value, the browser will show just a single image:

```css
body {
  /* All other properties remains the same */
  
  background-repeat: repeat-y;  /* change to this value */
}
```

The result in the browser:

![A non repeated image in the browser](https://thepracticaldev.s3.amazonaws.com/i/l9kht5nvu3bur3f0n6bx.PNG)

###__`background-attachment`__
The `background-attachment` specifies whether the background is fixed with regard to the viewport or scrolls along with the containing block.

__Populate your HTML with enough text__ that will allow the browser to add a scroll bar.

Another alternate way is to increase the text `font-size`.

Add this to your CSS:

```css
p {
  font-size: 4em;
}
```

Update the `body` element property declarations to match the following:

```css
body {
  background-image: url('img/hd_11.jpg');
  color: #ffffff;
  background-repeat: repeat;     /* tile the image both horizintally and vertically */
  background-attachment: fixed; /* the background image wont move when you scroll */
}
```

Save your files and refresh your browser. If you scroll, you will realize the background image is affixed to the viewport.

I have provided two images so that we can observe and notice the changes.

![a web page with a fixed background](https://thepracticaldev.s3.amazonaws.com/i/fmnihawzhz04ag55lugs.png)
<figcaption>A web page with fixed background</figcaption>

![a web page with a scroll background](https://thepracticaldev.s3.amazonaws.com/i/o9khf00o6j1gj86t8ml3.png)
<figcaption>A web page with background position set to scroll</figcaption>


###__`background-position`__
This property specify the initial position of the background image.  If we specify just one value the browser will assume the second value to be `center`.

If at least one value is not a keyword, then:

* The first value represents the horizontal position
* The second represents the vertical position.

Negative percentage and length values are allowed.

Update the `body` CSS rule to match the following:

```css
body {
  background-repeat:  no-repeat;
  background-color: #dddddd;
  background-position: 50% 10%;  /* Note this*/
}
```

Save and refresh your browser.

![A centered background image](https://thepracticaldev.s3.amazonaws.com/i/ljmd4l1hvrpduyewg6h7.PNG)

You can also specify the background position using keywords.

Here are some `background-position` that you can try out.

* `background-position: top right;`
* `background-position: bottom left;`
* `background-position: bottom;`
* `background-position: right;`

Please use the following [algorithm](https://en.wikipedia.org/wiki/Algorithm) to try out the codes above:

1. Update your `body` declaration with any of the background position and its value
2. Save your file
3. Refresh your browser and see the result
4. Go back to 1

###__`background`__
The `background` property  is a shorthand property for setting the individual background properties `background-color` , `background-image`, `background-repeat` , `background-attachment` and `background-position`  at the same place in your CSS.

The following code can be use to achieve almost everything we've demonstrated so far.

```css
body {
  color: #ffffff;

  /*
   * 1. image
   * 2. fallback color
   * 3. background-position
   * 4. background-repeat
   * 5. background-attachment 
  */
				/*1*/		 		/*2*/    /*3*/ /*4*/  /*5*/
	background: url('img/hd_11.jpg') #213a59 50%   repeat fixed;

}
```

<hr>

You might find yourself in situations where you have multiple repeated property declarations in your CSS code.

__How would you feel if you can just declare a property once and then use it multiple times.?__

That's when _CSS variables_ can be of great service and it's next.