【问题标题】:How to center one photo over another photo by CSS如何通过 CSS 将一张照片居中放置在另一张照片上
【发布时间】:2018-01-16 05:01:04
【问题描述】:

我可以通过以下代码将一张照片放在另一张照片上 但它并不完全位于另一张照片的中心。 如果前景照片大于背景照片。这应该 自动调整大小以适应中心。 我怎么能达到这个效果? 任何提示都将受到欢迎!

<!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>

【问题讨论】:

标签: css


【解决方案1】:

您可以通过几种方式实现它。但是正如您的课程所提到的,您可能正在寻找 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

【讨论】:

  • 感谢您的建议。我累了,它不起作用
【解决方案2】:

这是我刚刚制作的一个示例,创建一个嵌套 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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-08-16
    • 2019-05-04
    • 2012-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-23
    • 2020-05-21
    相关资源
    最近更新 更多