How to use all available space vertically in a CSS Grid?

前端 未结 2 742
孤街浪徒
孤街浪徒 2020-12-19 04:23

I\'m trying to build a web layout with a title bar, a nav header, a footer and a main content area in the middle (split in two for a sidebar and main view).

I intend

2条回答
  •  不知归路
    2020-12-19 04:46

    Solution

    Set grid height to the viewport height - add height: 100vh to the .grid and reset the default browser body margin to zero.


    Why

    This is because unless the container (for which you have given display: grid) has a set height, it will take only as much space as its contents. So when you give height there is available space now to fill into. See demo below:

    * {
      box-sizing: border-box;
    }
    body { /* ADDED */
      margin: 0;
    }
    
    .grid {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
      grid-template-rows: min-content min-content auto min-content;
      grid-gap: 10px;
      grid-template-areas: "header header" "nav nav" "sidebar main" "footer footer";
      height: 100vh; /* ADDED */
    }
    
    .title {
      grid-area: header;
      background-color: #1BC336;
    }
    
    .navigation {
      grid-area: nav;
      background-color: #C3A21B;
    }
    
    .sidebar {
      grid-area: sidebar;
      background-color: gold;
      overflow: auto;
    }
    
    .main {
      grid-area: main;
      background-color: #1BC3B9;
      overflow: auto;
    }
    
    .footer {
      grid-area: footer;
      background-color: #5C1BC3;
    }

    Title Bar

    Main content


    Should occupy all the remaining space.
    Test
    Test
    Test
    Test
    Test

提交回复
热议问题