防止弹性项目崩溃

时间:2018-03-28 21:00:17

标签: html css css3 flexbox overflow

如何修复标题并确保它会显示?

.cont {
  display: flex;
  flex-direction: column;
  width: 250px;
  height: 150px;
  border: 1px solid red;
  overflow: hidden;
}

.title {
  display: flex;
  background: #ccc;
  justify-content: space-between;
}
<div class="cont">
  <div class="title">
    <div>title that collapse</div>
    <div>28/3/2018</div>
  </div>
  <div>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Ab sapiente provident iure ipsa ipsum nulla distinctio vero nisi officiis, id accusantium perferendis enim quisquam. Optio est deserunt atque, explicabo enim excepturi aliquid expedita rerum
    voluptates similique ipsam vitae sapiente sequi at earum.
  </div>
</div>

https://codepen.io/anon/pen/xWYZEK

1 个答案:

答案 0 :(得分:4)

以下是解决此问题的两个选项:min-heightflex-shrink

使用min-height

而不是height: 150px使用min-height: 150px

由于你强制盒子有一个固定的高度,内部的内容会在必要时溢出。使用min-height,该框可以展开以容纳内容。

.cont {
  display: flex;
  flex-direction: column;
  width: 250px;
  min-height: 150px; /* adjustment */
  border: 1px solid red;
  overflow: hidden;
}
.title {
  display: flex;
  background: #ccc;
  justify-content: space-between;
}
<div class="cont">
  <div class="title">
    <div>title that collapse</div>
    <div>28/3/2018</div>
  </div>
  <div>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Ab sapiente provident iure ipsa ipsum nulla distinctio vero nisi officiis, id accusantium perferendis enim quisquam. Optio est deserunt atque, explicabo enim excepturi aliquid expedita rerum
    voluptates similique ipsam vitae sapiente sequi at earum.
  </div>
</div>

禁用flex-shrink

弹性容器的初始设置为flex-shrink: 1。这意味着允许flex项目缩小以避免容器溢出。

由于容器上有一个固定的高度,标题正在缩小,所以所有项目都可以放在里面。

因此,min-height选项的替代方法是禁用flex-shrink

.cont {
  display: flex;
  flex-direction: column;
  width: 250px;
  height: 150px; /* back to original */
  border: 1px solid red;
  overflow: hidden;
}
.title {
  flex-shrink: 0; /* new */
  display: flex;
  background: #ccc;
  justify-content: space-between;
}
<div class="cont">
  <div class="title">
    <div>title that collapse</div>
    <div>28/3/2018</div>
  </div>
  <div>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Ab sapiente provident iure ipsa ipsum nulla distinctio vero nisi officiis, id accusantium perferendis enim quisquam. Optio est deserunt atque, explicabo enim excepturi aliquid expedita rerum
    voluptates similique ipsam vitae sapiente sequi at earum.
  </div>
</div>