How to force child div to be 100% of parent div's height without specifying parent's height?

前端 未结 26 1647
刺人心
刺人心 2020-11-22 06:52

I have a site with the following structure:

<
相关标签:
26条回答
  • 2020-11-22 07:23

    This is a frustrating issue that's dealt with designers all the time. The trick is that you need to set the height to 100% on BODY and HTML in your CSS.

    html,body {
        height:100%;
    }
    

    This seemingly pointless code is to define to the browser what 100% means. Frustrating, yes, but is the simplest way.

    0 讨论(0)
  • 2020-11-22 07:24
    #main {
        overflow: hidden;
    }
    #navigation, #content {
        margin-bottom: -1000px;
        padding-bottom: 1000px;
    }
    
    0 讨论(0)
  • 2020-11-22 07:24

    using jQuery:

    $(function() {
        function unifyHeights() {
            var maxHeight = 0;
            $('#container').children('#navigation, #content').each(function() {
                var height = $(this).outerHeight();
                // alert(height);
                if ( height > maxHeight ) {
                    maxHeight = height;
                }
            });
            $('#navigation, #content').css('height', maxHeight);
        }
        unifyHeights();
    });
    
    0 讨论(0)
  • 2020-11-22 07:25

    After long searching and try, nothing solved my problem except

    style = "height:100%;"
    

    on the children div

    and for parent apply this

    .parent {
        display: flex;
        flex-direction: column;
    }
    

    also, I am using bootstrap and this did not corrupt the responsive for me.

    0 讨论(0)
  • 2020-11-22 07:25

    Here old fashion demo based on position: absolute of content container and position: relative of parent container.

    As for modern way to do it - flex boxes are the best.

    0 讨论(0)
  • 2020-11-22 07:32

    NOTE: This answer is applicable to legacy browsers without support for the Flexbox standard. For a modern approach, see: https://stackoverflow.com/a/23300532/1155721


    I suggest you take a look at Equal Height Columns with Cross-Browser CSS and No Hacks.

    Basically, doing this with CSS in a browser compatible way is not trivial (but trivial with tables) so find yourself an appropriate pre-packaged solution.

    Also, the answer varies on whether you want 100% height or equal height. Usually it's equal height. If it's 100% height the answer is slightly different.

    0 讨论(0)
提交回复
热议问题