【问题标题】:Make a 2 div inside a div share the space [duplicate]在 div 中创建 2 个 div 共享空间 [重复]
【发布时间】:2019-04-01 22:37:13
【问题描述】:

我在一个主 div 中有 2 个 div divA 和 divB,

divA 位于顶部,就像标题保持顶部一样,他有一个固定的高度。 divB 是内容,应该占据到底部的所有空间。

divA 有一个像素大小。 divB 应该是高度的 100% - divA 大小

    #container{
  width:400px;
  height:800px;
  background-color:red;
  position:relative;
  overflow: scroll;
}

#options{
  width:95%;
  height:30px;
  background: #734A6F;
  position: relative;
  color: #FFF;
  line-height: 33px;
  padding-left: 10px;
}

#buttons{
    position:absolute;
    width:95%;
    height:100%;
    background-color:blue;
}

<div id="container">
  <div id="options">

  </div>
   <div id="buttons">

  </div>
</div>

我不想隐藏滚动,所以请不要 scroll:hidden 在我的情况下,蓝色 div 里面有东西,所以它会在隐藏滚动的情况下被切成两半。使其正常工作的唯一方法是适合蓝色 div

https://codepen.io/crocsx-the-styleful/pen/GYLKKj

【问题讨论】:

  • 您的意思是 divB 应该从主 div(父级)继承全高吗?
  • 我用钢笔编辑了一下。 codepen.io/crocsx-the-styleful/pen/GYLKKj 底部有按钮(绿色)。 divB 应该是高度(父容器)的 100% - divA 大小。所以基本上因为容器是页面的 100%,divB 满足页面的 100% -divA 大小。例如,底部的按钮没有被剪掉
  • 查看计算函数:buttons.height: calc(100% - 30px);

标签: html css


【解决方案1】:

除非您正在寻找非常旧的浏览器支持,否则 CSS flexbox 让这一切变得非常简单。

display: flex; // use flexbox
flex-direction: column; // set flexbox to vertical
justify-content: flex-start; // start at the top

flex-basis: 30px; // how much height it takes up

flex: 2; // any number greater than 1 will cause it to fill the space

#container {
  width: 400px;
  height: 600px;
  background: red;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
}

#options {
  background: green;
  flex-basis: 30px;
}

#buttons {
  background: blue;
  flex: 2;
}
<div id="container">
  <div id="options">
    Div A
  </div>
  <div id="buttons">
    Div B
  </div>
</div>

【讨论】:

  • 不要将// 用于 cmets,您的代码已损坏且无法正常工作
  • 感谢修复
【解决方案2】:

我修改了你的 codepen 来实现这一点。基本上:

  1. divB 的上边距等于 divA 的高度。
  2. divA 将 position 设置为 absolute
  3. divB的Overflow设置为auto,所以当divB内容溢出时才会出现滚动条。

Codepen

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-25
    • 2021-09-21
    • 2010-10-26
    • 2018-07-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多