rrichter rrichter - 1 year ago 50
HTML Question

How do I position one image on top of another in HTML?

I'm a beginning rails programmer, attempting to show many images on a page. Some images are to lay on top of others. To make it simple, say I want a blue square, with a red square in the upper right corner of the blue square (but not tight in the corner). I am trying to avoid compositing (with ImageMagick and similar) due to perfomance issues.

I just want to position overlapping images relative to one another.

As a more difficult example, imagine an odometer placed inside a larger image. For six digits, I would need to composite a million different images, or do it all on the fly, where all that is needed is to place the six images on top of the other one.

Answer Source

Ok, after some time, here's what I landed on:

<div style="position: relative; left: 0; top: 0;">
  <img src="a.jpg" style="position: relative; top: 0; left: 0;"/>
  <img src="b.jpg" style="position: absolute; top: 30px; left: 70px;"/>

As the simplest solution. That is:

Create a relative div that is placed in the flow of the page; place the base image first as relative so that the div knows how big it should be; place the overlays as absolutes relative to the upper left of the first image. The trick is to get the relatives and absolutes correct.