如何在 HTML 中将一张图片放在另一张图片之上?

2022-01-30 00:00:00 optimization graphics html css

我是 Rails 编程的初学者,试图在一个页面上显示许多图像.有些图像要放在其他图像之上.为了简单起见,假设我想要一个蓝色方块,蓝色方块的右上角有一个红色方块(但角落不紧).由于性能问题,我试图避免合成(使用 ImageMagick 和类似方法).

I'm a beginner at rails programming, 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 performance 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.

推荐答案

好的,过了一段时间,我找到了:

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

.parent {
  position: relative;
  top: 0;
  left: 0;
}
.image1 {
  position: relative;
  top: 0;
  left: 0;
  border: 1px red solid;
}
.image2 {
  position: absolute;
  top: 30px;
  left: 30px;
  border: 1px green solid;
}

<div class="parent">
  <img class="image1" src="https://via.placeholder.com/50" />
  <img class="image2" src="https://via.placeholder.com/100" />
</div>

作为最简单的解决方案.那就是:

As the simplest solution. That is:

创建一个放置在页面流中的相对div;首先将基本图像放置为相对,以便 div 知道它应该有多大;将叠加层放置为相对于第一张图像的左上角的绝对值.诀窍是让相对和绝对正确.

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.

相关文章