如何将一个图像居中放置在另一个图像上 [英] How to center one image over another
问题描述
我有2张图像-一个是主图像,另一个是像相框,我想将其放置在主图像上方.相框图像是具有透明中心的png,因此主图像可以显示出来.
I have 2 images - one is the main image and the other is like a picture frame that I'd like to position over the top of the main image. The picture frame image is a png with a transparent center so the main image shows through.
图像的尺寸很重要-内部主图像必须小于框架,因此只能通过中心可见:
The dimensions of the images are important - the inner main image has to be smaller than the frame so it is only visible through the center:
main.jpg = 367 x 550
main.jpg = 367 x 550
frame.png = 405 x 597
frame.png = 405 x 597
我以为我使用以下代码...
I thought I had it with the following code...
<div style="background-image:url('/main.jpg') no-repeat scroll center center transparent;">
<img style="width:100%; max-width:100%;" src="/frame.png">
</div>
...非常有用,直到您在手机上看到屏幕为止;frame.png会拉伸,因为我已经将宽度设为100%,但背景main.jpg却没有随之拉伸.
...which works great until you see the screen on a mobile phone; the frame.png stretches because I've given the width as 100% but the background main.jpg doesn't stretch along with it.
我需要设计流畅,所以我需要拉伸图像.
I need the design to be fluid, so I need the images to stretch.
有没有办法确保背景的拉伸程度与主图像相同?
Is there a way to make sure the background stretches the same as the main image?
我尝试了各种不同的方法来使它正常工作,将帧绝对定位在div浮动在主图像上的位置,等等,但是当我这样做时,我无法使主图像在水平和垂直方向上居中显示
I've tried all kinds of different methods to get this working, absolutely positioning the frame in a div floating over the main image, etc but I couldn't get the main image to appear centered horizontally and vertically when I did that.
有什么方法可以不依靠javascript来实现我想要的吗?
Is there any way to achieve what I want without resorting to javascript?
我之所以使用2张图像,是因为文件大小.我需要主图像为jpg,以便可以将其缩小,但是我也需要框架上的透明性,因此必须为png:(
The reason I'm using 2 images by the way is because of file size. I need the main image to be jpg so I can keep it small, but I also need the transparency on the frame so that has to be png :(
推荐答案
我通常使用另一个绝对定位为背景的图像.像:
I generally use another image absolute positioned as background. like:
<div>
<img class="background-img" width="100%" height="100%" style="position:absolute; top:0; left:0">
<img class="second-img" width="100%" height="100%" />
<!-- Then do the positioning with classes -->
</div>
试一试,希望它能按需要工作
Give it a shot, hope it works as you want
这篇关于如何将一个图像居中放置在另一个图像上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!