CSS - How to force elements to 100% of remaining/a

2019-04-05 09:05发布

问题:

This seems like a really amateur question, in my opinion, but nonetheless it's still a frustrating anomaly.

This is actually the 2nd part of a 2 part problem. The first part is a rather common one, involving getting an element to stretch to 100% height of its parent object. In my demo, I have the following HTML:

<body>      
<div id="sbcontainer">
    DIV 1
    <div id="sbcontent">
        DIV 2
        <table id="sbmaintable" cellspacing="0">
            <tr>
                <td>
                    TABLE
                </td>
            </tr>
        </table> <!-- END MAINTABLE -->
    </div> <!-- END CONTENT -->
</div> <!-- END CONTAINER -->
</body>

I want each element here to fill all vertical space within its parent element. I tried used the following style on each of the elements (Please note that BODY and HTML are also set to 100% height in my demo):

min-height: 100%; 
height: auto !important; 
height: 100%; 

The result was as follows:

As you can see, the outermost DIV followed the 100% height property but the rest did not. As implied in the image note, but not actually shown in this image, I tried setting the 2nd DIV (red border) to a static height of 400px to see if the TABLE within would stretch to 100% height, and it still did not.

I then found that if I removed height:auto; from each of the elements, they would follow the 100% height property, but with an unwanted side effect:

As you can see in the image, each element is now truly 100% the height of its parent element, forcing the bottom to extend beyond the boundaries of its parent. (Even in my first example, the outermost DIV with the green border extended farther than desired because there is another sibling DIV above it on the page). NOTE: After looking more carefully, I can see that the blue TABLE element is not actually the same height as its red DIV parent, but it still extends beyond its boundary. I'm not sure if this means anything, but I do notice it.

One would think that this would be an easy thing to solve, but despite my efforts, I've had no success.

If I keep only height:auto; and remove the 100% properties, this does not stretch them at all.

I have searched for solutions on this via Google and StackOverflow, and although many sites covered 100% height issues, I still haven't found an actual solution.

I am currently testing this in Firefox.

回答1:

You can use absolute positioning.

#b {
    width: 40em;
    height: 20em;
    position:relative;
    background: red;
}
#c {
    position: absolute;
    top: 1em;
    bottom: 1em;
    left: 1em;
    right: 1em;
    background: blue;
}

<div id="b">
    <div id="c">
    </div>
</div>


标签: html css height