如何在HTML中将一个图像放置在另一个图像之上?

时间:2020-03-05 18:48:59  来源:igfitidea点击:

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

我只想相对于彼此放置重叠的图像。

举一个更困难的例子,想象一下将里程表放在更大的图像中。对于六位数,我将需要合成一百万个不同的图像,或者即时进行处理,其中所需要做的就是将六个图像放置在另一个图像之上。

解决方案

回答

最简单的方法是使用背景图片,然后在该元素中放入<img>。

另一种方法是使用css层。有大量资源可以解决此问题,只需搜索CSS图层即可。

回答

这是我为使一个图像浮动到另一个图像而做的简单研究。

img {
  position: absolute;
  top: 25px;
  left: 25px;
}
.imgA1 {
  z-index: 1;
}
.imgB1 {
  z-index: 3;
}
<img class="imgA1" src="https://placehold.it/200/333333">
<img class="imgB1" src="https://placehold.it/100">

来源

回答

下面的代码可能会给我们一些想法:

<style>
.containerdiv { float: left; position: relative; } 
.cornerimage { position: absolute; top: 0; right: 0; } 
</style>

<div class="containerdiv">
    <img border="0" src="https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png" alt=""">
    <img class="cornerimage" border="0" src="http://www.gravatar.com/avatar/" alt="">
<div>

JSFiddle

我怀疑Espo的解决方案可能不方便,因为它要求我们绝对放置两个图像。我们可能希望第一个在流程中定位自己。

通常,有一种自然的方法就是CSS。我们将position:relative放置在容器元素上,然后将子元素绝对放置在其中。不幸的是,我们不能将一个图像放在另一个图像中。这就是为什么我需要容器div。请注意,我将其设为浮动对象以使其自动适应其内容。使其显示:从理论上讲,内联块也应该可以工作,但是那里的浏览器支持很差。

编辑:我从图像中删除了大小属性,以更好地说明我的观点。如果我们希望容器图像具有其默认大小,并且事先不知道该大小,则不能使用背景技巧。如果这样做,这是一个更好的方法。

回答

内联样式仅是为了此处清晰。使用真实的CSS样式表。

<!-- First, your background image is a DIV with a background 
     image style applied, not a IMG tag. -->
<div style="background-image:url(YourBackgroundImage);">
    <!-- Second, create a placeholder div to assist in positioning 
         the other images. This is relative to the background div. -->
    <div style="position: relative; left: 0; top: 0;">
        <!-- Now you can place your IMG tags, and position them relative 
             to the container we just made -->   
        <img src="YourForegroundImage" style="position: relative; top: 0; left: 0;"/>
    </div>
</div>

回答

@ buti-oxa:不必脚,但代码无效。 HTML的width和height属性不允许单位。我们可能会想到CSS的width:和height:属性。我们还应该提供带有<style>标签的content-type(" text / css";请参见Espo的代码)。

<style type="text/css"> 
.containerdiv { float: left; position: relative; } 
.cornerimage { position: absolute; top: 0; right: 0; } 
</style>

<div class="containerdiv">
    <img border="0" src="http://www.gravatar.com/avatar/" alt="" width="100" height="100">
    <img class="cornerimage" border="0" src="http://www.gravatar.com/avatar/" alt="" width="40" height="40">
<div>

在width和height属性中保留px;可能会导致渲染引擎瘫痪。

回答

好的,过了一段时间,这就是我的目标:

.parent {
  position: relative;
  top: 0;
  left: 0;
}
.image1 {
  position: relative;
  top: 0;
  left: 0;
}
.image2 {
  position: absolute;
  top: 30px;
  left: 70px;
}
<div class="parent">
  <img class="image1" src="https://placehold.it/50" />
  <img class="image2" src="https://placehold.it/100" />
</div>

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

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