【问题标题】:How can I specify the dimensions of the flex container and make the flex items to scroll within the container?如何指定弹性容器的尺寸并使弹性项目在容器内滚动?
【发布时间】:2022-08-15 16:22:28
【问题描述】:

我用 flexbox 创建了一个图片库,但它比电脑屏幕大。这使得 flexbox 滚动。问题是在我的页面中弹性框上方有一个导航栏,当弹性框向上滚动屏幕时它会重叠。所以我希望 flexbox 容器有一个特定的尺寸和在其中滚动的项目,而不是整个盒子在屏幕上滚动。请提出解决方案。

.gallery_container {
  background-color: rgba(243, 239, 236, 0.7);
  padding: 10px;
}

.gallery_header {
  text-align: center;
  font-family: calibri;
}

.photo_container {
  display: flex;
  background-color: rgba(0, 0, 0, 1);
  flex-direction: row;
  flex-wrap: wrap;
  justify-content: center;
  align-items: center;  
}

.photo_container img {
  object-fit: cover;
  width: 45%;
  height: 400px;
  margin: 5px;
}
  <div class=\"gallery_container\">
    <h2 class=\"gallery_header\">Gallery</h2>
    <div class=\"photo_container\">
        <img src=\"photoA.jpg\">
        <img src=\"photoB.jpg\">
        <img src=\"photoC.jpg\">
        <img src=\"photoD.jpg\">
    </div>
  </div>
  • 添加最大高度或特定高度并声明溢出规则。

标签: html css flexbox


【解决方案1】:

我在您的photo_container 中添加了更多照片。这样,在所有尺寸的屏幕上都可以更好地看到滚动效果。

要限制photo_container 的高度,需要在类中添加height 属性。只要这个height 小于屏幕视口的高度就可以了。您可以尝试以下方法之一,例如:

    height: 200px;
    height: 50%;
    height: 75vh;

height: 50%; 不起作用,因为在其父级 gallery_container 上没有设置 height。但是其他两个效果很好,具体取决于您的用例。让我们设置height: 75vh;,这意味着高度为视口高度的75%,这可能是你想要的,

photo_container 现在大小合适,但所有图像都溢出了容器。

要解决此问题,您需要通过将 overflow-y: scroll; 添加到类中来在 photo_container div 上创建滚动条。这应该对你有用。

你可以在这里阅读MDN docs about CSS values and units including vh

你可以在这里阅读MDN docs about overflow-y

这是您进行上述更改的代码:

.gallery_container {
  background-color: rgba(243, 239, 236, 0.7);
  padding: 10px;
}

.gallery_header {
  text-align: center;
  font-family: calibri;
}

.photo_container {
  display: flex;
  background-color: rgba(0, 0, 0, 1);
  flex-direction: row;
  flex-wrap: wrap;
  justify-content: center;
  align-items: center;
  height: 75vh;
  overflow-y: scroll;
}

.photo_container img {
  object-fit: cover;
  width: 45%;
  height: 400px;
  margin: 5px;
}
<div class="gallery_container">
  <h2 class="gallery_header">Gallery</h2>
  <div class="photo_container">
    <img src="photoA.jpg">
    <img src="photoB.jpg">
    <img src="photoC.jpg">
    <img src="photoD.jpg">
    <img src="photoA.jpg">
    <img src="photoB.jpg">
    <img src="photoC.jpg">
    <img src="photoD.jpg">
    <img src="photoA.jpg">
    <img src="photoB.jpg">
    <img src="photoC.jpg">
    <img src="photoD.jpg">
  </div>
</div>

【讨论】:

    猜你喜欢
    • 2021-11-01
    • 1970-01-01
    • 2021-07-19
    • 1970-01-01
    • 2017-10-22
    • 1970-01-01
    • 2018-02-21
    相关资源
    最近更新 更多