首页 > 解决方案 > 如何使内容重叠的 div 随窗口大小缩放并居中?

问题描述

我有多个图像要放置在一个 div 中,彼此重叠(主要是在每个 png 图像的透明背景中)。我想让整个图像集在 div 范围内并重新定位以使其看起来相同,但随着浏览器窗口大小的变化而尺寸变小。我怎样才能做到这一点,并让 div 在浏览器窗口中水平居中?

我有一个 JSFiddle 中遇到的问题的示例:

https://jsfiddle.net/vug5yrdb/16/

<html>

<head>
    <meta charset="utf-8">
    <style type="text/css">
        .gwd-img-1kkt {
          position: absolute;
          left: 1.76%;
          top: 1.04%;
          width: 25.2%;
          height: 47.24%;
        }

        .gwd-img-1c79 {
          position: absolute;
          left: 2.08%;
          top: 28.88%;
          width: 25.2%;
          height: 29.2%;
        }
        .gwd-img-12uj {
          position: absolute;
          left: 0.06%;
          top: -7.61%;
          width: 35.22%;
          height: 79.77%;
        }

        .wrapper {
          position:relative;
          padding: 100%;
        }
    </style>
</head>

<body>
    <div class="wrapper">
        <img src="https://i.imgur.com/KG8oR83.png" id="red-bit" class="gwd-img-1kkt">
        <img src="https://i.imgur.com/GQqpTkb.png" id="teal-bit" class="gwd-img-1c79">
        <img src="https://i.imgur.com/iBIXHX3.png" id="blue-bit" class="gwd-img-12uj">
    </div>
</body>

</html>

此版本可适当缩放,但未居中并被拉伸。

标签: htmlcss

解决方案


您可以像下面这样调整您的代码。我添加了一个边框来说明居中:

.gwd-img-1kkt {
  position: absolute;
  left: 20.52%;
  top: 2.08%;
  width: 50.4%;
  height: 94.48%;
}

.gwd-img-1c79 {
  position: absolute;
  left: 21.16%;
  top: 57.76%;
  width: 50.4%;
  height: 58.4%;
}

.gwd-img-12uj {
  position: absolute;
  left: 17.12%;
  top: -15.22%;
  width: 70.44%;
  height: 159.54%;
}

.wrapper {
  position: relative;
  width:50%; /* this will control the horizontal size*/
  margin:50px auto;
  outline:1px solid;
}
.wrapper::before {
  content:"";
  display:block;
  padding-top:70%; /* this will control the vertical size */
}
<div class="wrapper">
  <img src="https://i.imgur.com/KG8oR83.png" id="red-bit" class="gwd-img-1kkt">
  <img src="https://i.imgur.com/GQqpTkb.png" id="teal-bit" class="gwd-img-1c79">
  <img src="https://i.imgur.com/iBIXHX3.png" id="blue-bit" class="gwd-img-12uj">
</div>


推荐阅读