How to get the content of the bottom element of a flexbox to be 100% height its container

前端 未结 2 832
攒了一身酷
攒了一身酷 2021-01-05 15:21

If I make a flexbox with 2 children and column flow and set the second child to flex-grow 1 the second child expands to fill the flexbox. This works

(p

2条回答
  •  有刺的猬
    2021-01-05 15:53

    How do I get #bottom to stretch to fit the flexbox and also get a the child #inside to be 100% height of its container #bottom?

    Just add two lines of code to the CSS.

    CSS

    #bottom {
        background-color: blue;
        flex: 1 0 auto;
        display: flex; /* NEW */
    }
    
    #inside {
        flex: 1; /* NEW */
        background-color: green;
    }
    

    DEMO: http://jsfiddle.net/wf2L8dse/

    Here's what's happening:

    You have a flex container (#outer) with two flex items (#top and #bottom).

    #outer is in column alignment.

    #bottom has flex: 1 (i.e., flex-grow: 1), so it occupies all available height in the container.

    A new element (#inside) is made a child of #bottom and must occupy the same height as parent.

    Solution:

    Make #bottom a (nested) flexbox. This activates default flex rules.

    One such rule is align-items: stretch, which tells flex items (#inside) to stretch the full height of their container. (Height, in this case, because the flex-direction is row, by default.)

    Then apply flex: 1 (or flex-grow: 1) to #inside, so it expands the full width of the container.


    Addressing the height: 100% issue

    I'm not sure there's anything wrong with your code. You have applied height: 100% to #inside and, as required by the spec when using percentage heights, specified a height for all parent elements including body and the root element (html).

    The only thing you may want to consider (to remove the vertical scrollbar on the browser window), is applying overflow: hidden to body.

    DEMO: http://jsfiddle.net/wf2L8dse/1/

提交回复
热议问题