loading...

CSS Backgrounds

ziizium profile image Habdul Hazeez ・7 min read

FrontEnd Development Zero to Hero (67 Part Series)

1) FrontEnd Development: Zero to Hero 2) What is the Internet 3 ... 65 3) What is the Web 4) Web Browsers 5) Tools for Web Development 6) Introduction to HTML 7) History of HTML 8) The HTML specification 9) HTML Elements and Tags 10) Replaced Element and Void Element 11) Writing Accessible HTML 12) Validating HTML documents 13) HTML Resources and Reference 14) Introduction to CSS 15) History of CSS 16) The CSS Specification 17) CSS Properties 18) CSS Selectors 19) CSS Units 20) CSS Specificity 21) The CSS Cascade 22) CSS Inheritance 23) The CSS Box model 24) CSS Margin Collapse 25) CSS Positioning 26) CSS z-index 27) CSS colors 28) CSS Backgrounds 29) CSS Variables 30) CSS Floats 31) CSS Block Formatting Context 32) CSS Flexbox part 1 33) CSS Flexbox part 2 34) CSS Grid part 1 35) CSS Grid part 2 36) CSS Media Queries 37) CSS Typography 38) CSS Animations and Transitions 39) CSS Naming conventions 40) Writing maintainable CSS 41) CSS References and Resource 42) Introduction to JavaScript 43) History of JavaScript 44) The EcmaScript specification 45) Introduction to programming 46) JavaScript Variables 47) JavaScript Arrays 48) JavaScript Objects 49) JavaScript Numbers 50) JavaScript Conditionals 51) JavaScript Loops 52) JavaScript Functions 53) The Document Object Model 54) Introduction to Ajax 55) JavaScript References and Resource 56) Introduction to Web Design 57) History of web design 58) Site Layouts in CSS 59) Introduction to Responsive web design 60) Introduction to Progressive Enhancement 61) Introduction to User Interface design 62) Introduction to user experience design 63) Introduction to Web accessibility and usability 64) Introduction to Color theory 65) Web design References and resource 66) Series final project 67) Building your career as a developer

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.

<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>
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 Firefox 70 web browser and its Developer Tools.


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, 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

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.

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

Then what happens if the image fails to load?

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

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

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

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

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

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 — The image is repeated both horizontally and vertically.
  • repeat-x — The image is repeated horizontally only.
  • repeat-y — The image is repeated vertically only.
  • no-repeat — The image is not repeated: only one copy of the image is drawn.
  • inherit — 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:

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

Now update your body declaration with the following:

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

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

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

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

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

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:

p {
  font-size: 4em;
}

Update the body element property declarations to match the following:

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

A web page with fixed background

a web page with a scroll background

A web page with background position set to scroll

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:

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

Save and refresh your browser.

A centered background image

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 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.

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;

}

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.

FrontEnd Development Zero to Hero (67 Part Series)

1) FrontEnd Development: Zero to Hero 2) What is the Internet 3 ... 65 3) What is the Web 4) Web Browsers 5) Tools for Web Development 6) Introduction to HTML 7) History of HTML 8) The HTML specification 9) HTML Elements and Tags 10) Replaced Element and Void Element 11) Writing Accessible HTML 12) Validating HTML documents 13) HTML Resources and Reference 14) Introduction to CSS 15) History of CSS 16) The CSS Specification 17) CSS Properties 18) CSS Selectors 19) CSS Units 20) CSS Specificity 21) The CSS Cascade 22) CSS Inheritance 23) The CSS Box model 24) CSS Margin Collapse 25) CSS Positioning 26) CSS z-index 27) CSS colors 28) CSS Backgrounds 29) CSS Variables 30) CSS Floats 31) CSS Block Formatting Context 32) CSS Flexbox part 1 33) CSS Flexbox part 2 34) CSS Grid part 1 35) CSS Grid part 2 36) CSS Media Queries 37) CSS Typography 38) CSS Animations and Transitions 39) CSS Naming conventions 40) Writing maintainable CSS 41) CSS References and Resource 42) Introduction to JavaScript 43) History of JavaScript 44) The EcmaScript specification 45) Introduction to programming 46) JavaScript Variables 47) JavaScript Arrays 48) JavaScript Objects 49) JavaScript Numbers 50) JavaScript Conditionals 51) JavaScript Loops 52) JavaScript Functions 53) The Document Object Model 54) Introduction to Ajax 55) JavaScript References and Resource 56) Introduction to Web Design 57) History of web design 58) Site Layouts in CSS 59) Introduction to Responsive web design 60) Introduction to Progressive Enhancement 61) Introduction to User Interface design 62) Introduction to user experience design 63) Introduction to Web accessibility and usability 64) Introduction to Color theory 65) Web design References and resource 66) Series final project 67) Building your career as a developer

Posted on by:

ziizium profile

Habdul Hazeez

@ziizium

I teach and write code with interests in Web Development, Computer Security, and Artificial Intelligence.

Discussion

markdown guide
 

do not use background-attachment: fixed; it is not working (properly) on mobile devices :)

caniuse.com/#feat=background-attac...