Lesson 2: Positioning Elements

1. Save the image of the cat and dog below to your game folder (in the same location as your index.html file) that you created in Lesson 1. The steps for doing this may vary between browers, but you will probably be able to right-click on the image and select "Save Image As..." or something similar. If you choose to use your own images, be sure you edit them to have transparent backgrounds.

2. Add the images to gameWindow. Give each image an id, and use this id to style them. The ids will also be used in JavaScript to select elements and do things with them, like move them around the screen.

Notice this puts the images next to each other. The position of cat effects the position of dog.

If a CSS property is not assigned to an Element, the browser will use the default value.

For example, the default value for background-color is transparent.
The default value for the position of an element is static.

3. In most games, the elements in gameWindow will need to move about without affecting other elements, and even be capable of overlapping in the same space. This is where positioning comes into play. Give the gameWindow a position of relative and give the elements inside of gameWindow, i.e. cat and dog, a position of absolute.

This means that the position of the elements cat and dog will have an absolute position relative to gameWindow. Since the default value for left and top are both zero, the images are positioned at the top, left corner of gameWindow.

4. Modify the CSS so that there is one style for dog and another style for cat.

Notice that both images are being positioned relative to the gameWindow. For instance, the cat has been pushed down 10px from the top of the gameWindow, and pushed 50px over from the left side of the gameWindow. Only use left and top to position an element. Avoid using right or bottom.

The top and left properties are used only for elements with an absolute position.

5. When using absolute positioning, the z-index allows you to move elements in front and behind each other. If you are familiar with Photoshop, this is just like layers. Give dog a z-index of 1 and give cat a z-index of 2.

An element with a higher z-index will appear in front of an element with a lower z-index. Since cat has a larger z-index, it will appear in front of dog.

Now you know how to place elements in the gameWindow!

Test Yourself!

1. The left and top CSS properties can be used
only with elements that have a position of relative
only with elements that have a position of absolute
onlt with elements that have a position of absolute or relative
with all elements, regardless of the position
2. The _________ value is the value of a property that is not explicitly set in code.
3. What is the default value for the position property of a div?
4. What property specifies the stack order of overlapping elements?