02. Applying Backgrounds background-image, background-color, background-size

Background Color

You can specify a color for a background in case you want a basic color.

To do so, simply use the background-color property with a color value.

#sample {
  height: 5em;
  width: 10em;
  color: white;
  background-color: purple;
  border: 1px solid purple;
  border-radius: 5px;
  margin: 0 auto;
  padding: 5px;
  text-align: center;
}
A simple div element with a purple background color.

Applying a Background Image

To specify a particular image, we use the background-image value with an absolute or relative link to the image inside a url() value.

Grabbing from within your own server

Here is an example of how to grab an image named paper-background.jpg that is located in the img folder within the root directory.

#sample {
  background-image: url("/img/paper-background.jpg");
  height: 4em;
  width: 15em;
  padding: 5px;
  margin: 0 auto;
  border-radius: 5px;
  font-weight: bold;
  text-align: center;
}
A simple div element with a paper-background.

Grabbing from another server

We can also use a full address to grab it from another server.

background-image: url("https://imgur.com/path/here");

Background Size

In the previous example, we just placed the background, and set the width and height of its containing element.

To set size of the background image itself, we use the background-size property. The first value is the height, while the second is the width.

#sample {
  background-size: 100px 20px;
}

Be sure that the dimensions are scaled properly. If they are not, this will distort (or stretch out) your image. To avoid this problem, simply specify the value you'd like to use, then auto for the other value.

#sample {
  background-size: 100px auto;
} 

We simply add this property to the example above.

background-image: url("/img/paper-background.jpg")
A simple div element with a properly fitting background.

You can see that this background example is scaled so that it can fit within our containing element.

Aching back from coding all day?

Acupressure Mat & Pillow

Aching back from coding all day? Try Back Problems

Relieve your stress, back, neck and sciatic pain through 1,782 acupuncture points for immediate neck pain relief. Made for lower, upper and mid chronic back pain treatment, and improves circulation, sleep, digestion and quality of life.

$$ Check price
144.87144.87Amazon 4.5 logo(1,890+ reviews)

More Back Problems resources

Build modern and responsive webpages

JavaScript & JQuery

Build modern and responsive webpages Try Front-end

This book was written for anyone who wants to use JavaScript to make their websites a little more interesting, engaging, interactive, or usable. In particular, it is aimed at people who do not have a degree in computer science (well, not yet anyway).

$ Check price
39.9939.99Amazon 4.5 logo(385+ reviews)

More Front-end resources

Ad