Add scroll to each column in CSS Grid Layout

前端 未结 2 449
春和景丽
春和景丽 2020-12-31 13:28

I want separate scroll on each of my columns in my grid layout.

Currently, I am developing a mobile only web application. I want to use a different grid layout for t

2条回答
  •  情话喂你
    2020-12-31 14:17

    In the landscape orientation I want to use 2 columns. My whole content is displayed on the left side and my navigation moves to the right side. Now I want both parts to have a separate scroll. Is there a way to implement this? And the scroll should stop if the content of the current column ends.

    In the left column you have three separate grid items: the header, main and footer elements.

    In the right column you have one grid item: the nav element.

    Adding a scrollbar – vertical or horizontal – to the left column is not feasible because there are three separate elements. You would need to wrap all elements in a container for a single scrollbar to work.

    Adding a scrollbar – vertical or horizontal – to the right column is pretty easy because there is only one element.

    Assuming that you're talking about a vertical scrollbar, here's one way to make it work:

    body {
      margin: 0;
    }
    
    .grid-container {
      display: grid;
      grid-template-columns: 1fr;
      grid-template-rows: 1fr;
      grid-gap: 15px 0;
      height: 100vh;
    }
    
    header {
      background-color: green;
      grid-column: 1;
      grid-row: 1
    }
    
    main {
      background-color: blue;
      grid-column: 1;
      grid-row: 2;
    }
    
    nav {
      background-color: pink;
      grid-column: 1;
      grid-row: 3;
      overflow: auto;
    }
    
    footer {
      background-color: teal;
      grid-column: 1;
      grid-row: 4;
    }
    
    @media only screen and (orientation: landscape) {
      .grid-container {
        grid-template-columns: 5fr 4fr;
        grid-template-rows: 1fr 1fr 1fr;
      }
      nav {
        grid-column: 2;
        grid-row: 1 / span 3;
      }
      footer {
        grid-row: 3;
      }
    }

    Logo

    content

    Footer

    revised codepen


    Browser Support for CSS Grid

    • Chrome - full support as of March 8, 2017 (version 57)
    • Firefox - full support as of March 6, 2017 (version 52)
    • Safari - full support as of March 26, 2017 (version 10.1)
    • Edge - full support as of October 16, 2017 (version 16)
    • IE11 - no support for current spec; supports obsolete version

    Here's the complete picture: http://caniuse.com/#search=grid

提交回复
热议问题