我是rails编程的初学者,试图在一个页面上显示许多图像。有些图像是放在其他图像之上的。简单地说,假设我想要一个蓝色正方形,在蓝色正方形的右上角有一个红色正方形(但在角落里不紧)。我试图避免合成(与ImageMagick和类似)由于性能问题。
我只是想让重叠的图像彼此相对。
作为一个更困难的例子,想象一个里程表放在一个更大的图像中。对于六位数字,我需要合成一百万个不同的图像,或者在飞行中完成,其中所需要的只是将六张图像放在另一张图像的顶部。
我是rails编程的初学者,试图在一个页面上显示许多图像。有些图像是放在其他图像之上的。简单地说,假设我想要一个蓝色正方形,在蓝色正方形的右上角有一个红色正方形(但在角落里不紧)。我试图避免合成(与ImageMagick和类似)由于性能问题。
我只是想让重叠的图像彼此相对。
作为一个更困难的例子,想象一个里程表放在一个更大的图像中。对于六位数字,我需要合成一百万个不同的图像,或者在飞行中完成,其中所需要的只是将六张图像放在另一张图像的顶部。
当前回答
Here is a solution that worked for me. Assuming all the images to be stacked are inside a div container, all you need to do is to set the display property of the div to flex. Don't set any position for the first image but for every other image, set the position property to absolute. Finally, use z-index to control the layers. You can set the first image's z-index to 1, the second image's z-index to 2, and so on (In my own case, I set the z-index of every other image apart from the first image to 2). If you want to center the images, you can set the justify-content property of the div to center to align the images horizontally to the center and adjust the top property to align the images vertically to the center. The values you use for the justify-content and top properties depend on the size of your images and whether the sizes are responsive on different devices or not. Here's my example:
img { 边框:2px纯红色; } .img1n2 { 显示:flex; justify-content:中心; } .img1 { z - index: 1; } .img2 { 位置:绝对的; z - index: 2; 上图:52.5%; } < div class = " img1n2”> <img class="img1" src="https://fakeimg.pl/400/"> <img class="img2" src="https://fakeimg.pl/300/" width="100"> <img class="img2" src="https://fakeimg.pl/200/" width="50"> <img class="img2" src="https://fakeimg.pl/50/" width="30"> < / div >
实际上,你可以用这个方法叠加一千或一百万张图像。您可以使用CSS来满足您的特定需求。编码快乐!
其他回答
简单的方法是使用background-image,然后在该元素中放入<img>。
另一种方法是使用css图层。有大量的资源可以帮助你做到这一点,只要搜索css图层。
我注意到一个可能导致错误的问题是,在rrichter的回答中,下面的代码:
<img src="b.jpg" style="position: absolute; top: 30; left: 70;"/>
应该在样式中包含px单元。
<img src="b.jpg" style="position: absolute; top: 30px; left: 70px;"/>
除此之外,答案还不错。谢谢。
你可以使用CSS-Grid,这是一个非常方便的解决方案,如果你想堆叠,重叠内容。首先需要定义网格。在该网格中,您“告诉”img-tags在该网格中的位置。如果将它们定义为位于网格的同一起点,则它们将重叠。在下面的例子中,两个图像重叠,一个在它们下面。
< span style=" font - family:宋体;Grid-template-columns: [first-col] 100%;Grid-template-rows:[第一行]300px"> <img src="https://fakeimg.pl/300/" style=" font - family:宋体;grid-row-start:板凳”> <img src="https://fakeimg.pl/300/" style=" font - family:宋体;grid-row-start:板凳”> < img src = " https://fakeimg.pl/300/ " > < / div >
你可以在这里找到一个关于CSS-Grid的很好的解释。
这是我所做的使一个图像漂浮在另一个图像上的一个粗略的观察。
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">
源
设置背景大小的封面。然后用另一个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>