使用可变高度的周围元素最大化div的高度

Fin*_*nnb 6 html javascript css jquery css3

我有一个div,我希望最大化,在父母的基础上100vh.

问题是我有两个pdiv,它们也可以根据窗口的宽度改变它们的高度,从而导致不同的大小.

现在,快速和肮脏的解决方案可能只是运行一个jQuery片段检测母体的大小div以及p基于这些div,并设置div的高度上运行的功能doc.readywindow.onresize.

但这感觉不必要,我想知道是否有一个更简洁的解决方案只使用我不知道的CSS?

我已经在下面设置了一个简化但不起作用的问题版本,看看你是否能比我所指的更清楚.

任何提示都会很棒,谢谢!

*{
  margin: 0;
  padding: 0;
  font-family: Arial, san-serif;
}

#parent{
  height: 100vh;
  background: lightblue;
}

p{
  font-size: 40px; 
  background: yellow;
 }

#p1{
  top: 0;
}

#p2{
  bottom: 0;
  position: absolute;
}

div{
  background-color: red;
  height: 100%;
}
Run Code Online (Sandbox Code Playgroud)
<div id="parent">
  <p id="p1">Long block that only appears on the top</p>
  <div>Maximising Div</div>
  <p id="p2">Long block that only appears on the bottom</p>
</div>
Run Code Online (Sandbox Code Playgroud)

Ric*_*cky 3

您可以通过 实现您想要的目标flexbox

由于关于如何使用的资源有很多flexbox,因此不会包含在本答案的范围内。不过,我将解释基础知识,以便您能够了解这里发生的情况。

  1. 您定义一个容器,在本例中#parent使用属性 display: flex;,这使其成为一个弹性容器。
  2. 该容器的子元素现在是弹性项目,在您的情况下是 <p>元素和<div>中间的。
  3. 然后,我们让中间部分<div>增长,以填充具有速记属性的容器的可用空间flex: 1;

代码片段:

* {
  margin: 0;
  padding: 0;
  font-family: Arial, san-serif;
}
#parent {
  height: 100vh;
  background: lightblue;
  display: flex;
  flex-direction: column;
}
p {
  font-size: 40px;
  background: yellow;
}
div > div {
  background-color: red;
  flex: 1;
}
Run Code Online (Sandbox Code Playgroud)
<div id="parent">
  <p id="p1">Long block that only appears on the top</p>
  <div>Maximising Div</div>
  <p id="p2">Long block that only appears on the bottom</p>
</div>
Run Code Online (Sandbox Code Playgroud)


笔记:

  • 检查迈克尔的答案以了解当前的浏览器支持。