如何调整 div 元素,使网站在不同屏幕尺寸的设备上看起来相同?

How can I adjust div elements so that the website looks the same on devices of different screen sizes?

我有一个网站,我定期将框(div 元素称为 post-it)添加到宽度为 100% 的较大 div 元素(称为部分)。 section 元素是除网站 headers 之外的整个网站。我对盒子使用了绝对定位,并根据顶部和左侧像素设置了它们在网站上的位置。

.section{
    width: 100%;
    height: 1000px;
    margin: 0 auto;
    background-repeat: repeat-y;
    background-size:contain;
    background-color: #8B8B8B;
}

.post-it{
    height: 100px;
    width: 100px;
    font-family: 'Monte', sans-serif;
    font-size: 25;
    padding-top: 56.25%;

}

<header>
    <p>Sample header of webpage</p>
</header>
<div class="section">
    <div class = "post-it" style = "position: absolute; top: 640px; left: 20px;">
    .
    .
    .
    <div class = "post-it" style = "position: absolute; top: 1450px; left: 870px;">
    .
    (arbitrary amount of post-its added at different times)
</div>
<footer>
    <p>Sample footer of webpage</p>
</footer>

当我在笔记本电脑上时,我可以在较大的 div 元素的最右侧添加一个框,这样网站显示就不会中断。但是,当我在屏幕较小的 phone 上刷新同一页面时,整个网站缩小到浏览器 window 的 top-left 并且 post-it 处于空闲状态在白色背景上,这不是我编码的一部分。

此外,当我在桌面上调整浏览器 window 时,一些 post-it 被裁掉了。作为参考,我没有在网站上使用 table 进行布局。 如何调整 div 元素,使网站在不同屏幕尺寸的设备上看起来一样?

已更新 - 硬编码位置

.section 应将 position 设置为 relative 以指定 absolute 定位的子元素锚定到它。然后,您可以尝试使用百分比来确保子元素的位置在不同视口上保持在 .section 范围内。

但是,当仅使用内联样式和绝对位置时,无法确保 absolute 定位元素将保持预期位置而不与不同大小的视口上的其他元素重叠。

如果您必须使用绝对定位,则需要为硬编码到 HTML 中的每个 .post-it 创建 ID。然后,在您的 styles.css 中,为不同的视口大小指定 media queries

我在这里演示了媒体查询和绝对位置:https://codepen.io/sevanbadal/pen/ExjBKEg

这非常乏味,因为您必须为每个 .post-it 硬编码新的 id。然后在 CSS 中将 id 添加到您指定的每个媒体查询中。

原始响应 - 使用弹性布局

您可以使用 CSS Flexbox 布局。查看 Mozilla CSS Flexbox 文档了解详细信息。

对于您的问题,请将 flex 应用到您的 "section" class。然后使用 justify-content 调整任意数量的 div 在 flex 布局中的显示方式。 Flex-wrap 也可以用来将 flex-layout 的内容分成多行。

您可能想要 remove/change 来自 .post-it 的填充。

在 .section 上尝试此代码:

.section{
  width: 100%;
  height: 1000px;
  background-repeat: repeat-y;
  background-size:contain;
  background-color: #8B8B8B;

  display: flex;
  flex-wrap: wrap;
}

这就是 .post-it

.post-it{
  height: 100px;
  width: 100px;
  font-family: 'Monte', sans-serif;
  font-size: 25;
}