CSS Backgrounds and Borders Module Level 3: Specifying Background and Border Styles
This tutorial demonstrates how you can create a background for your application.
Warm-up
Become familiar with the CSS Backgrounds and Borders Module Level 3 API basics by learning about:
-
Creating Backgrounds
Create a multilayer background with the parallax effect.
Creating Backgrounds
To enhance the user experience of your application, you must learn to create a multilayer background with the parallax effect using the CSS box model. The background consists of 3 images on separate layers, and 2 of the layers can be moved over each other.
Figure: Background with the parallax effect
- Prepare 3 images (tizen.png, tizen2.png, and dot.png), each with a transparent background.
- Create a div element with id="parallelexample" and a slider input element with the minimum, maximum, and initial value:
<div id="parallelexample"></div> <input id="position" type="range" min="1" max="200" value="50">
- Define the needed styles for the div element in the <head> section using the parallelexample ID.
Define a background using the prepared images in the correct order. The images are shown in the order they have been added, with the first image on the topmost layer. Use the same order when defining the background position for each image.
#parallelexample { width: 300px; height: 300px; background-image: url(tizen2_32.png), url(tizen3_32.png), url(dot.png); background-position: 6.25em 8em, 3.125em 4em, center top; background-repeat: repeat, repeat, repeat; border: 1px solid black; margin: 0px auto; }
- To create the parallax effect, create a method that moves the background layers by changing the horizontal position values of the images in the div element. To determine the position value change, add an onchange event handler for the slider to determine the change based on the slider handle movement.
function moveLayers() { /* Get slider value */ var poz = document.getElementById('position'); /* Get the div element */ var example = document.getElementById('ParallaxExamle'); /* Add the event handler */ poz.onchange = function() { var layer1 = this.value/8, layer2 = this.value/16; example.style.backgroundPosition = layer1 +'em 8em, ' + layer2 + 'em 4em, center top'; } }
Source Code
For the complete source code related to this use case, see the following files: