CSS大小调整 - 将子级限制为父级维度

时间:2017-06-12 05:25:49

标签: html css css3 flexbox

我正在尝试设计一个特定页面,与下面的代码非常相似。 JS Fiddle

#body {                   /* is actually absolute positioned  */
  width: 800px;
  height: 400px;
}

#parent {
  display: flex;
}

#child1 {
  flex: 1;
  overflow: auto;
  background-color: yellow;
}

#child2 {
  flex: 0 0 150px;
  background-color: green;
}

#big {
  width: 900px;
  height: 490px;
  background-color: white;
}
<div id="body">
  <div id="dummy">
    <!-- Other content here -->
    <div id="parent">
      <div id="child1">
        <div id="big"></div>
      </div>
      <div id="child2"></div>
    </div>
  </div>
</div>

我需要添加到页面上元素的最小CSS是什么,以便 div永远不会超过 body div的维度。

2 个答案:

答案 0 :(得分:2)

要使子元素尊重高度,其父元素必须具有集合height

我在这里添加了height / max-height(请参阅CSS中的评论)

#body {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
}

#dummy {                   /*  added #dummy  */
  display: flex;           /*  for IE 11  */
  width: 100%;
  height: 100%;
}

#parent {
  display: flex;
  flex: 1;                  /*  for IE 11  */
  max-height: 100%;         /*  added property  */
  max-width: 100%;          /*  added property  */
}

#child1 {
  flex: 1;
  overflow: auto;  
  background-color: yellow;
}

#child2 {
  flex: 0 0 150px;
  background-color: green;
}

#big {
  width: 900px;
  height: 490px;
  background-color: white;
}
<div id="body">
  <div id="dummy">
    <div id="parent">
      <div id="child1">
        <div id="big"></div>
      </div>
      <div id="child2"></div>
    </div>
  </div>
</div>

答案 1 :(得分:0)

将高度设置为 100vh 而不是 100%,因为在高度的情况下,视口设备的工作效率高于百分比。 重写 flex 代码,该代码将支持以下及其新版本: IE 10,Safari 6,Firefox 20,Opera 12

&#13;
&#13;
#body, #dummy, #parent {
  width: 100%;
  height: 100vh;
}

#body {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100vh;
}

#dummy {              
  position: relative;
  float: left;
}

#parent {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-flex: 1;
      -ms-flex: 1;
          flex: 1;               
}

#child1 {
  -webkit-box-flex: 1;
      -ms-flex: 1;
          flex: 1;
  overflow: auto;  
  background-color: yellow;
}

#child2 {
  -webkit-box-flex: 0;
      -ms-flex: 0 0 150px;
          flex: 0 0 150px;
  background-color: green;
}

#big {
  width: 900px;
  height: 490px;
  background-color: white;
}
&#13;
<div id="body">
  <div id="dummy">
    <div id="parent">
      <div id="child1">
        <div id="big"></div>
      </div>
      <div id="child2"></div>
    </div>
  </div>
</div>
&#13;
&#13;
&#13;