强制元素根据兄弟宽度进行换行

时间:2017-08-18 13:04:23

标签: html css css3 flexbox

正如您在下面的代码段和图片中看到的那样,我有一个包含主要元素(绿色)和页脚的容器(灰色)。

页脚本身包含两个元素(蓝色和黄色)。

我想要的是,如果页脚(蓝色+黄色)比主要元素(绿色)宽,则页脚第二个元素(黄色)会换行。

我为那些不想播放该片段的人附上一张照片:

screenshot from the snippet

我尝试在页脚上使用flex-wrap,但仅当我在页脚上设置宽度时才有效,我不想这样做。



.container {
  background-color: grey;
  display: inline-block;
}

.narrow-child {
  background-color: green;
  height: 200px;
  width: 100px;
}

.large-child {
  background-color: green;
  height: 200px;
  width: 300px;
}

.footer {
  display: flex;
  flex-wrap: wrap;
  /*width: 100px;*/
}

.footer-sub-element1 {
  background-color: blue;
  width: 80px;
  height: 50px;
}

.footer-sub-element2 {
  background-color: yellow;
  width: 90px;
  height: 50px;
}

<div class="container">
  <div class="narrow-child">
  </div>
  <div class="footer">
    <div class="footer-sub-element1">
    </div>
    <div class="footer-sub-element2">
    I want this to wrap
    </div>
  </div>
</div>

<div class="container">
  <div class="large-child">
  </div>
  <div class="footer">
    <div class="footer-sub-element1">
    </div>
    <div class="footer-sub-element2">
    I don't want this to wrap
    </div>
    </div>
  </div>
</div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:2)

.footer的宽度不能在不使用JavaScript的情况下依赖兄弟。解决方案是定义.container的宽度而不是.child

.container {
  background-color: grey;
  display: inline-block;
}

.narrow {
  width: 100px;
}

.large {
  width: 300px;
}

.child {
  background-color: green;
  height: 200px;
}

.footer {
  display: flex;
  flex-wrap: wrap;
  /*width: 100px;*/
}

.footer-sub-element1 {
  background-color: blue;
  width: 80px;
  height: 50px;
}

.footer-sub-element2 {
  background-color: yellow;
  width: 90px;
  height: 50px;
}
<div class="container narrow">
  <div class="child">
  </div>
  <div class="footer">
    <div class="footer-sub-element1">
    </div>
    <div class="footer-sub-element2">
    I want this to wrap
    </div>
  </div>
</div>

<div class="container large">
  <div class="child">
  </div>
  <div class="footer">
    <div class="footer-sub-element1">
    </div>
    <div class="footer-sub-element2">
    I don't want this to wrap
    </div>
    </div>
  </div>
</div>