我是rails编程的初学者,试图在一个页面上显示许多图像。有些图像是放在其他图像之上的。简单地说,假设我想要一个蓝色正方形,在蓝色正方形的右上角有一个红色正方形(但在角落里不紧)。我试图避免合成(与ImageMagick和类似)由于性能问题。

我只是想让重叠的图像彼此相对。

作为一个更困难的例子,想象一个里程表放在一个更大的图像中。对于六位数字,我需要合成一百万个不同的图像,或者在飞行中完成,其中所需要的只是将六张图像放在另一张图像的顶部。


当前回答

设置背景大小的封面。然后用另一个div包装你的div,现在设置max-width在父div上。

<div style="max-width:100px">
  <div style="background-image:url('/image.png'); background-size: cover; height:100px; width:100px; "></div>
</div>

其他回答

创建一个相对的div,放在页面的流中;将基本图像放在相对位置,这样div就知道它应该有多大;相对于第一张图片的左上方,将重叠图层放置在绝对位置。诀窍在于正确使用亲戚和绝对。

你完全可以相对于它们的父元素来定位伪元素。

这为每个元素提供了两个额外的层-因此将一个图像放置在另一个图像之上变得很容易-具有最小的语义标记(没有空div等)。

标记:

<div class="overlap"></div>

css:

.overlap
{
    width: 100px;
    height: 100px;
    position: relative;
    background-color: blue;
}
.overlap:after
{
    content: '';
    position: absolute;
    width: 20px;
    height: 20px;
    top: 5px;
    left: 5px;
    background-color: red;
}

这里是一个现场演示

内联样式只是为了清晰起见。使用真正的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>

这可能有点晚了,但你可以这样做:

HTML

<!-- html -->
<div class="images-wrapper">
  <img src="images/1" alt="image 1" />
  <img src="images/2" alt="image 2" />
  <img src="images/3" alt="image 3" />
  <img src="images/4" alt="image 4" />
</div>

SASS

// In _extra.scss
$maxImagesNumber: 5;

.images-wrapper {
  img {
    position: absolute;
    padding: 5px;
    border: solid black 1px;
  }

  @for $i from $maxImagesNumber through 1 {
    :nth-child(#{ $i }) {
      z-index: #{ $maxImagesNumber - ($i - 1) };
      left: #{ ($i - 1) * 30 }px;
    }
  }
}

这是我所做的使一个图像漂浮在另一个图像上的一个粗略的观察。

img { 位置:绝对的; 上图:25 px; 左:25 px; } .imgA1 { z - index: 1; } .imgB1 { z - index: 3; } <img class="imgA1" src="https://via.placeholder.com/200/333333"> <img class="imgB1" src="https://via.placeholder.com/100">