1

我花了很长时间在谷歌上搜索我(相对)简单的问题的答案,但一直找不到。

我想在我们的基于 Web 的业务应用程序中有一个框(div?),它的高度是其父容器的 100%。在那个盒子里,应该有 2 个盒子,彼此叠放。

  • 顶框应根据其内容调整大小。(永远不会超过总高度的 50%)。
  • 底部的盒子应该得到其余的高度。任何溢出都应该滚动。

最好不要使用 javascript,尤其是不要每 x 毫秒轮询一次高度的 javascript 计时器。

这是结果的模型: 问题的图像

这个问题有解决方案吗?

4

1 回答 1

2

查看第三版,这是最好的解决方案


我相信与此类似的东西尽可能接近(假设它们的结构与我相信的一样)

/* HTML */
<div id='container'>
    <div id='top'></div>
    <div id='bottom'></div>
</div>

/* CSS */
#container {
    width:300px; /* I assume the width/height is fixed */
    height:200px;
    border: 1px solid black;
    padding:4px; /* To remove the horiz scrollbar with width:100% and a border */
    overflow:hidden; /* Hide the content at the bottom to allow scroll */
}
#top {
    width:100%;
    max-height:50%; /* Using max-height allows it to size to smaller content */
    overflow:auto; /* Allow a scrollbar if necessary */
}
#bottom {
    height:100%; /* Take up the remaining space */
    overflow:auto; /* Allow a scrollbar if necessary */
}

演示在这里

附带说明一下,您的问题应包括问题、与问题相关的代码以及您对解决方案的尝试。这样我们就可以准确了解您的问题是什么,看到您自己尝试过解决方案,并使用您的实际代码来修复它


编辑

为了完全按照你的意愿得到它,你可以使用一点 javascript

var parent = document.getElementById('container'),
    top = parent.children[0],
    bottom = parent.children[1];

bottom.style.height =  parent.offsetHeight - top.offsetHeight - 8 + "px";
// The 8 comes from the vertical padding of the parent + 4 (not sure what the 4 
// is from, probably the four vertical padding widths). The actual number could
// be calculated dynamically, but that would require using getComputedStyle and
// is more work than it's worth since borders/padding don't change dynamically

演示在这里

如果您不关心格式,那么您可以通过

document.getElementById('bottom').style.height = document.getElementById('container').offsetHeight - document.getElementById('top').offsetHeight - 8 + "px";

需要 Javascript,因为您不能像您希望的那样在纯 CSS 中基于另一个元素的可变高度设置高度。更多信息offsetHeight看这里


第二次编辑

如果你必须让它响应输入(我用过contenteditable),你可以使用onclickandonkeyup事件将函数绑定到它。你应该拥有所有你需要的工具来让它按照你现在想要的方式进行,我不可能确切地知道你想要什么或你希望它如何表现

top.onkeyup = function() {
    bottom.style.height =  parent.offsetHeight - top.offsetHeight - 8 + "px";
}
top.onkeyup();
top.onclick = function() {
    top.onkeyup();
}

演示在这里


第三次编辑

不知道为什么我以前没有考虑过这一点,但这对于 flexbox 来说是一个完美的情况。它更简单、更直观、更易于操作。PS 我在演示中包含了浏览器前缀

#container {
    ...
    overflow:hidden; /* Hide overflow */
    /* I excluded vendor prefixes for the sake of brevity, they're in the demo */
    flex-flow: column; /* Makes content flow down instead of across */    
    display: flex;
}
#top {
    ...
    max-height:50%; /* Sets the max height... */
    overflow:auto; /* Make sure scrollbar is there */        
    box-flex: none;
    flex: none; /* In essence, this acts like `height:auto` */
}
#bottom {
    ...
    border:1px solid red;
    overflow:auto; /* Make sure scrollbar is there */        
    flex: 2; /* Can be any positive number in this case */
}

很棒的 CSS 演示在这里。有关 flexbox 的更多信息,请查看这篇文章这个视频系列和帖子,以及一些示例。但是,在我看来,学习它的最好方法是自己尝试项目

于 2013-11-13T15:59:20.467 回答