HTML Cookbook Basic HTML Course

It's Easy!


Alternate Version

CSS Positioning, Part 2

In our last lesson, we learned how to place an element on a page. Essentially we learned how to place an image in a 2-dimensional space. In this lesson we will place an image on top of another image with absolute positioning. By now I imagine you have already figured out how to do this.

In our lesson on CSS Dimensions, we placed an image in a div that was larger than the image and we learned that we can add a background-image to the div, so we know that we can make a "scene" using an "object" image on top of a "landscape" image.

Now let's position an image on top of a background-image.

To do this you need:

  1. a div with an id for the background image
  2. another div with an id for each image that you want to place. The images div's go inside the background div, like so:
Layout Example
<div id="bg">

   <div id="image1">
   <img src="image1.gif" />
   </div>

   <div id="image2">
   <img src="image2.gif" />
   </div>

</div>

The 's go in an internal stylesheet, as in our last lesson.

The background image can be a texture or a scene. I made a demo page of each.


Demo Pages


Image on a texture

I'll use a small texture image, which will repeat.

The image can be anything. I'll use a sailboat.

I need an id for my background and another id for my boat.

CSS in Stylesheet
#boat_bg {
position:absolute;
left:0px;
top:0px;
width: 360px;
height: 360px;
background-image:
url(../bg/water.gif)
}

#boat_image {
position:absolute;
left:180px;
top:180px;
}


Code on Page
<div class="boat_bg">

<img id="boat_image"
src="../images/sailboat.gif"
width="107"
height="160"
alt="sailboat" />

</div>


Result: Sailing (screenshot).

I could move the background-image to the body and use the whole page. Later in the course, we'll learn how to move the sailboat across the page.


Image On a Scene

For this demo, I will use a woodland scene as the background-image in my div. I have a teddy bear I want to place in the woods.

Again, I need a div with an id for the background and another div with a an id for the image.

CSS In Stylesheet
#teddy_bg {
position:absolute;
left:0px;
top:0px; width:360px;
height:265px;
background-image:url(../images/fall_lane_lg.jpg);
}

#teddy {
position:absolute;
left:180px;
top:150px;
}


Code on Page
<div id="teddy_bg">
<div id="teddy">
<img src="../images/teddy_bear1.gif"
width="77" height="90"
alt="teddy bear on a country lane in the fall" />
</div>

Here is Teddy taking a walk in the woods (screenshot).

By adding more id's, I can have a whole family of teddy bears: Papa Bear, Mama Bear and Baby Bear. I used the same teddy bear image at different sizes. (screenshot).


Assignment

Place an image on top of a larger image using absolute positioning.

Happy coding!
Gnubee

Links
Tips
Tools
References
Rules
HTML Help Gnubee - Newsgroup
HTML Course Contents (Home)

Valid XHTML 1.0!

Valid CSS!