包含溢出内容的Flexbox项目仅适用于Chrome

Fel*_*ler 7 html css cross-browser css3 flexbox

请看看这支笔:

https://codepen.io/linck5/pen/gRKJbY?editors=1100

body{ margin: 0;}

.container {
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.top-bar {
  background-color: darksalmon;
  height: 50px;
}

.inner-container {
  flex: 1;
  background-color: chocolate;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.top {
  background-color: blueviolet;
  flex: 1;
  overflow: auto;
  font-size: 40px;
  line-height: 5rem;
}

.bottom {
  background-color: darkkhaki;
  height: 200px;
}
Run Code Online (Sandbox Code Playgroud)
<div class="container">
    
  <div class="top-bar">Top bar</div>

  <div class="inner-container">

    <div class="top">
      O<br>v<br>e<br>r<br>f<br>l<br>o<br>w<br>i<br>n<br>g<br>C<br>o<br>n<br>t<br>e<br>n<br>t
    </div>
    <div class="bottom">Bottom part</div>

  </div>
  
</div>
Run Code Online (Sandbox Code Playgroud)

我想只有.topdiv可滚动,而不是整个页面.我不希望.topdiv推下.bottomdiv.

这正是Chrome上发生的事情,一切都很完美.但是在Firefox和Edge上,整个页面上都会出现一个滚动条,并且.bottomdiv被按下.

.top-bardiv 也缩小了,而没有达到理想的50px高度.

你能帮助我吗?

Mic*_*l_B 7

需要考虑的三件事:

  1. 弹性项目的初始设置是flex-shrink: 1.这意味着允许项目缩小以便在容器中创建更多空间.要禁用此功能,请使用flex-shrink: 0.

    有关完整说明,请参阅此文章:flex-basis和width之间有什么区别?

  2. 弹性项目的初始设置是min-height: auto.这意味着项目不能小于其内容的高度.要覆盖此行为,请使用min-height: 0.

    有关完整说明,请参阅此文章:为什么Flex项目不会缩小内容大小?

  3. 在您的代码中,Firefox和Edge严格遵守规范.Chrome似乎认为规范是基础,但是常识场景中的因素和预期的用户行为.

要使您的布局能够跨浏览器工作,请进行以下调整:

body{ margin: 0;}

.container {
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.top-bar {
  background-color: darksalmon;
  height: 50px;
  flex-shrink: 0; /* NEW */
  /* Or remove height and flex-shrink and just use this: 
     flex: 0 0 50px; */
}

.inner-container {
  flex: 1;
  background-color: chocolate;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  min-height: 0; /* NEW */
}

.top {
  background-color: blueviolet;
  flex: 1;
  overflow: auto;
  font-size: 40px;
  line-height: 5rem;
}

.bottom {
  background-color: darkkhaki;
  /* height: 200px; */
  flex: 0 0 200px; /* NEW */
  
}
Run Code Online (Sandbox Code Playgroud)
<div class="container">
  <div class="top-bar">Top bar</div>
  <div class="inner-container">
    <div class="top">
O<br>v<br>e<br>r<br>f<br>l<br>o<br>w<br>i<br>n<br>g<br>C<br>o<br>n<br>t<br>e<br>n<br>t
    </div>
    <div class="bottom">Bottom part</div>
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)

修改过的笔