如何将CSS中的一张照片放在另一张照片上
问题描述:
我可以通过下面的代码 将另一张照片放在另一张照片上,但它并不完全位于另一张照片的中央。如果前景照片比背景照片大,则为 。它应该 自动调整大小以适应中心。 我怎么能达到这个效果? 任何提示将超过欢迎!如何将CSS中的一张照片放在另一张照片上
<!Doctype>
<html>
<head>
<style>
.background
{
position:relative;
top: 10px;
left: 10px;
z-index: 1;
margin: 0 auto;
}
.foreground
{
position:absolute;
top: 25px;
left: 25px;
z-index: 2;
margin: 0 auto;
}
</style>
</head>
<body>
<img src="frame.png" class="background" >
<img src="foreground.png" class="foreground">
</body>
</html>
答
你可以通过很少的方式实现它。但是当你的班级提到你可能正在寻找一个div的背景和前景图像。你应该使用尝试这样的事情
<body>
<div class="container">
<img src="foreground.png" class="foreground">
</div>
</body>
和风格它的CSS:
.container{
background-image: url("frame.png");
background-size: cover;
}
,如果你的IMG大小变化尝试添加:
img {
position: absolute;
margin: auto;
top: 0;
left: 0;
right: 0;
bottom: 0;
}
检查也:How to make an image center (vertically & horizontally) inside a bigger div
+0
谢谢你的建议。我累了,它不起作用 – stewchicken
答
下面是我刚刚创建的一个示例,创建一个嵌套div并将图像作为它们的图像背景。居中嵌套的div,并给他们每种高度和宽度。如果你希望你的前景图像缩小,如果你给前景图像一个百分比宽度,它永远不会比父图像大。
.background{
height:400px;
width:100%;
display:block;
background-image:url("http://www.fillmurray.com/400/900");
background-size:cover;
background-position:center center;
}
.foreground{
height:300px;
width:50%;
display:block;
margin:auto;
background-image:url("http://www.fillmurray.com/200/300");
background-size:cover;
background-position:center center;
position: relative;
top: 50%;
transform: translateY(-50%);
}
<!Doctype>
<html>
<body>
<div class="background">
<div class="foreground">
</div>
</div>
</body>
</html>
可以在关系的兄弟姐妹没有定位到另一个。使用包装并放置其中一个孩子。 –
看到这个问题https://stackoverflow.com/questions/37485593/css-center-any-image-in-div/37485686#37485686 –