css/JavaScript 调整 div 内容的大小以适合窗口

时间:2021-04-29 09:53:51

标签: javascript html css

我有一个页面,其中有很多图像位于另一张图像的顶部。 较小图像的位置是相对的,使用 px 给出左侧和顶部的距离。 当我缩放窗口时,图像集合会移动并停留在正确的位置。但我希望它在调整窗口大小时也能缩放。 (图像的比例应该保持不变,但更小/更大。) 所有图像都包含在一个重叠的 div 中。

有没有什么方法可以让我在不必重新定位所有图像的情况下做到这一点? (我对 css/JavaScript 很陌生)

以下是正在发生的事情的示例:https://codepen.io/gwenvere/pen/MWJdvJp 我想要的是红球留在山顶上,但如果窗户变小,山和球就会缩小。

以下是其中一张较小图像的 css 示例:

  position: relative;
  left: 161.7px;
  top: 208.7px;
  width: 79px;
  height: 79px;
  background-color: rgba(56, 152, 236, 0);
  background-image: url('../images/Medium.png');
  background-position: 0px 0px;
  background-size: cover;
}

大图的css:

.image-11 {
  position: absolute;
  left: 0%;
  top: 148px;
  right: 0%;
  bottom: 0%;
  width: 1200px;
  max-width: 1200px;
  margin-top: -37px;
  margin-right: auto;
  margin-left: auto;
}

重叠div的css:

.div-block-3 {
  position: relative;
  width: 1200px;
  height: 800px;
  max-height: none;
  max-width: none;
  min-height: auto;
  min-width: auto;
  margin-right: auto;
  margin-left: auto;
  background-color: rgba(83, 39, 39, 0);
  -webkit-transform-origin: top left;
}

1 个答案:

答案 0 :(得分:1)

Codepen 中的图像设置为 position: absolute 的固定宽度和高度,分别为 1200 像素和 800 像素,因此不会调整大小。

当您对问题的描述谈到调整窗口大小时,我假设您希望主图像放大和缩小,并使红点保持在相同的相对位置。

使用 CSS 的一种方法是使用宽度和高度的百分比来定位红点,并使用宽度的百分比来缩放点的大小(使用比率来设置点的高度。

body {
    padding: 0;
    margin: 0;
}
.body {
    position: relative;
    width: 100%;
    max-width: 1200px;
    margin-top: 147px;
    margin-right: auto;
    margin-left: auto;
    background-color: rgba(83, 39, 39, 0);
}

.largeImage {
    width: 100%;
    height: auto;
}

.smallImage {
    display: block;
    position: absolute;
    left: 57.5%;
    top: 26.17%;
    width: 6.67%;
    height: auto;
    transform: translate(-50%,50%);
    background-color: rgba(56, 152, 236, 0);
    background-image: url("https://upload.wikimedia.org/wikipedia/commons/thumb/3/31/Circle_Burgundy_Solid.svg/1024px-Circle_Burgundy_Solid.svg.png");
    background-position: 0px 0px;
    background-size: cover;
    margin: 0 auto;
}

.smallImage::before {
    display: block;
    padding-top: 100%;
    content: "";
}

.smallImage a {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
}
<div class="body">
    <img src="https://media.sproutsocial.com/uploads/2017/02/10x-featured-social-media-image-size.png" loading="lazy" alt="" class="largeImage">
    <div class="smallImage">
        <a href="#videoPlayer" id="smallBtn"></a>
    </div>
</div>

我在图像上方添加了一个边距,就像您在 Codepen 中那样。