Child height to be 100% of scrollable parent conte

2019-04-08 07:50发布

问题:

Please consider this fiddle: http://jsfiddle.net/eKJAj/

I'm trying to have an absolute positioned div (the red line) to take the whole height of the total height of its (yellow) parent ; not just the parent's visible height.

If you try the fiddle you'll see the red bar doesn't go the whole way down when you scroll the yellow div. Also it can't be bigger than its parent if some blue sections are removed.

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)" />

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;
}

I have been trying a few options for the blue bar such as top:0px; botom:0px or position:relative; margin-left:50px and even made an attemps with floating the red line, to no avail.

If possible I'd rather keep it CSS only. Any hint much appreciated!!

回答1:

One solution is to wrap your .parent in a(nother) container.

JSFiddle.

Set your .parent's container to have the max-height and overflow-y instead:

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

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

The reason it's not working in your example is because you're setting the maximum height to 300px. The 100% height .bar is then assuming a height of 300px. With this workaround, your .parent divider doesn't have a 300px height limit, but the outer .container does instead.