首页 > 解决方案 > 父级的堆叠 div 最大宽度

问题描述

我有一个 flexbox,它充当层叠在一起的 div 堆栈的容器。这个 div 有一个高度、宽度、最小高度和最小宽度集。

问题是一个或多个“层”div 可能包含大于容器设置尺寸的背景图像。

因为我在图层图像上将位置设置为绝对位置,所以它会扩展到父 div 边界之外。

我正在寻找一种不需要在图层 div 上设置高度和宽度的解决方案。有吗?

    .stack-container {
        height: 800px;
        min-height: 400px;
        width: 1000px;
        min-width: 600px;
    }
    .layer {
        position: absolute;
        background-repeat: no-repeat;
        background-position: center;
        background-size: cover;
    }
<div class="stack-container">
       <div class="layer"></div>
       <div class="layer"></div>
       <div class="layer"></div>
       <div class="layer"></div>
    </div>

标签: htmlcss

解决方案


在您的图层类上设置width: 100%,它将自行调整为父元素的当前宽度。

.stack-container {
  position: relative;
  height: 800px;
  min-height: 400px;
  width: 1000px;
  min-width: 600px;
  overflow: hidden;
}

.layer {
  position: absolute;
  width: 100%;
  background-repeat: no-repeat;
  background-position: center;
  background-size: cover;
  background: blue;
  color: white;
}
<div class="stack-container">
   <div class="layer" style="width: 1100px;">test</div>
   <div class="layer" style="width: 2100px;">test</div>
   <div class="layer" style="width: 5000px;">test</div>
   <div class="layer" style="width: 10000px;">test</div>
</div>


推荐阅读