使用flexbox,强制列包装文本而不是导致容器从其父级溢出

时间:2018-01-31 23:37:45

标签: html css css3 flexbox

我有一个有三列的弹性容器。中间栏填充左右之间的空间。当容器变窄时,我需要强制左右列包装它们的文本,而不是将容器挤出到页面的右侧。我怎么能这样做?



#main-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 30px;
  max-width: 100%;
}

#center-content {
  border: 1px solid green;
  flex: 1 1 auto;
}

#left-content, #right-content {
  flex: 0 0 auto;
  border: 1px solid red;
}

.box {
  height: 20px;
  height: 100%;
}

  <div id="main-container">
    <div id="left-content" class="box">
      asdf asdf asdf asdf asdf asdf asdf asdf asdf asdf asdf asdf
    </div>
    <div id="center-content" class="box">
      asdf asdf asdf asdf asdf asdf asdf asdf asdf asdf asdf asdf
    </div>
    <div id="right-content" class="box">
      asdf asdf asdf asdf asdf asdf asdf asdf asdf asdf asdf asdf
    </div>
  </div>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:1)

您可以在flex: 1元素上使用#center-content

#main-container {
  display: flex;
}
#center-content {
  border: 1px solid green;
  flex: 1;
}
#left-content,
#right-content {
  border: 1px solid red;
}
<div id="main-container">
  <div id="left-content" class="box">
    asdf asdf asdf asdf asdf asdf asdf asdf asdf asdf asdf asdf
  </div>
  <div id="center-content" class="box">
    asdf asdf asdf asdf asdf asdf asdf asdf asdf asdf asdf asdf
  </div>
  <div id="right-content" class="box">
    asdf asdf asdf asdf asdf asdf asdf asdf asdf asdf asdf asdf
  </div>
</div>

答案 1 :(得分:1)

flex属性更改为0 auto。请查看CSS-Tricks about Flexbox上的这个方便指南。具体来说,关于您使用的简写flex属性的部分:

  

这是flex-grow,flex-shrink和flex-basis组合的简写。第二和第三个参数(flex-shrink和flex-basis)是可选的。默认值为0 1 auto。

你的问题是因为你告诉灵活的项目与其他兄弟元素相比“增长”太多了。

#main-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 30px;
  max-width: 100%;
}

#center-content {
  border: 1px solid green;
  flex: 0 auto;
}

#left-content, #right-content {
  flex: 0 auto;
  border: 1px solid red;
}

.box {
  height: 20px;
  height: 100%;
}
  <div id="main-container">
    <div id="left-content" class="box">
      asdf asdf asdf asdf asdf asdf asdf asdf asdf asdf asdf asdf
    </div>
    <div id="center-content" class="box">
      asdf asdf asdf asdf asdf asdf asdf asdf asdf asdf asdf asdf
    </div>
    <div id="right-content" class="box">
      asdf asdf asdf asdf asdf asdf asdf asdf asdf asdf asdf asdf
    </div>
  </div>