我有一个 div,我想在基于 100vh 的父级中最大化其大小。
问题是我有两个 p
div,它们也可以根据窗口的宽度改变它们的高度,从而导致不同的大小。
现在快速而肮脏的解决方案可能只是运行一个 jQuery 片段来检测父 div
和 p
div 的大小,并根据这些设置 div 的高度,在 doc.ready
和 window.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%;
}
<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>
最佳答案
您可以通过 flexbox
实现您想要的效果.
因为有很多关于如何使用flexbox
的资源, 则不在本回答范围内。不过,我将解释基础知识,以便您了解这里发生的事情。
- 您定义一个容器,在本例中为
#parent
与属性(property)display: flex;
,这使它成为一个 flex 容器。 - 这个容器的子元素现在是 flex 元素,在你的例子中
<p>
元素和<div>
在中间。 - 然后我们让中间的
<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;
}
<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>
注意事项:
- 检查迈克尔的 answer 当前浏览器支持。
关于javascript - 最大化具有可变高度的周围元素的div的高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40031226/