子高度为可滚动父内容高度的100%

Joh*_*ann 7 html css height overflow

请考虑这个小提琴:http://jsfiddle.net/eKJAj/

我正在尝试使用绝对定位的div(红线)来获取其(黄色)父级的总高度的整个高度; 不仅仅是父母的可见高度.

如果您尝试小提琴,您将看到当您滚动黄色div时,红色条不会完全向下.如果删除了一些蓝色部分,它也不能大于其父级.

HTML:

<div class="parent">
    <div class="bar"></div>
    <div class="section"></div>
    <div class="section2"></div>
    <div class="section2"></div>
    <div class="section2"></div>
    <div class="section2"></div>
    <div class="section2"></div>
    <div class="section"></div>
</div>

<input type="button" value="hide" onclick="$('.section2').slideUp(400)" />
<input type="button" value="show" onclick="$('.section2').slideDown(400)" />
Run Code Online (Sandbox Code Playgroud)

CSS:

.parent{
    position:relative;
    width:100%; max-height:300px;
    background-color:yellow;
    overflow-y:auto;
}

.bar{
    position:absolute; left:50px;
    width:1px; height:100%;
    background-color:red;
}

.section, .section2{
    width:100%; height:70px;
    margin-bottom:3px;
    background-color:blue;
}
Run Code Online (Sandbox Code Playgroud)

我一直在尝试蓝色条的一些选项,top:0px; botom:0px或者position:relative; margin-left:50px甚至做了浮动红线的尝试,但无济于事.

如果可能的话我宁愿只保留CSS.任何提示非常赞赏!!

Jam*_*lly 6

一种解决方案是将您包裹.parent在(另一个)容器中.

JSFiddle.

设置你.parent的容器max-height,overflow-y而不是:

<div class="container">
    <!-- parent in here -->
</div>

.container {
    max-height:300px;
    overflow-y:auto;
}
.parent{
    position:relative;
    width:100%;
    background-color:yellow;
}
Run Code Online (Sandbox Code Playgroud)

它在您的示例中不起作用的原因是因为您将最大高度设置为300px.然后100%高度.bar假设高度为300px.通过此解决方法,您的.parent分隔符没有300px的高度限制,但外部.container确实如此.