Flex sidebar: how to grow to 100% of height

前端 未结 3 1879
小鲜肉
小鲜肉 2021-01-25 13:42

I´m building a sidebar using CSS flex and I need it to grow vertically to fill the whole screen vertical height. Here is a skeleton of what I´m doing.

JSFiddle here

3条回答
  •  忘掉有多难
    2021-01-25 14:14

    The proper usage of Flexbox, is to make the app take full height by either use height: 100vh, or give html/body a height, html, body { height: 100% } so the app's height work as expected.

    Second, as you use align-items: flex-start all items will initially align at the top, but by adding align-self: stretch to the sidebar, it will fill its parent's height.

    Note, for flex row item you should not use height: 100%, you should use the align-* properties.

    Note 2, the set flex: 1 on content-header and content-main doesn't have any affect, unless their parent content has a height higher than their summed height. i.e. if to change the app's align-items to stretch (and if, the align-self on sidebar can be removed)

    Note 3, the flex: 1 won't work properly in IE, use flex-grow: 1 instead, or assign all values, where flex-basis should be auto, i.e. flex: 1 1 auto

    Stack snippet

    body {
      margin: 0;
    }
    .app {
      display: flex;
      flex-direction: row;
      align-items: flex-start;
      height: 100vh;                 /*  changed  */
      width: 100%;
    }
    
    .sidebar {
      background-color: red;
      align-self: stretch;            /*  added  */
    }
    
    .content {
      width: 100%;
      display: flex;
      flex-direction: column;
    }
    
    .content-header {
      flex: 1;                        /*  for IE, "flex-grow: 1" or "flex: 1 1 auto" 
     */
      background-color: grey;
    }
    
    .content-main {
      flex: 1;                        /*  for IE, "flex-grow: 1" or "flex: 1 1 auto" 
     */
      background-color: yellow;
    }
    Content Header
    This is the main content

提交回复
热议问题