How to make a column span full width when a second column is not there? (CSS Grid)

前端 未结 3 558
后悔当初
后悔当初 2020-12-02 01:57

I know there are similar questions but this is specifically asking how to do this using CSS Grid Layout.

So we have this basic grid setup:

HTML (with

3条回答
  •  佛祖请我去吃肉
    2020-12-02 02:16

    I think I know the definitive answer to this question now. The problem with the answers so far is that they don't explain how to handle a sidebar that is on the left side of the main content (mainly because I didn't ask for it in the original question).

    content

    You can use this CSS:

    .grid {
      display: grid;
      grid-template-columns: fit-content(200px) 1fr fit-content(200px);
    }
    
    nav, aside {
      width: 100%;
    }
    
    /* ensures that the content will always be placed in the correct column */
    nav { grid-column: 1; }
    main { grid-column: 2; }
    aside { grid-column: 3; }
    

    This is also a good use case for grid-areas

    .grid {
      display: grid;
      grid-template-columns: fit-content(200px) 1fr fit-content(200px);
      grid-template-areas: "nav content sidebar";
    }
    
    nav, aside {
      width: 100%;
    }
    
    /* ensures that the content will always be placed in the correct column */
    nav { grid-area: nav; }
    main { grid-area: content; }
    aside { grid-area: sidebar; }
    

    An IE compatible version would look like this:

    .grid {
      display: -ms-grid;
      display: grid;
      -ms-grid-columns: auto 1fr auto;
      grid-template-columns: auto 1fr auto;
    }
    
    nav, aside {
      width: 100%; /* Ensures that if the content exists, it takes up max-width */
      max-width: 200px; /* Prevents the content exceeding 200px in width */
    }
    
    /* ensures that the content will always be placed in the correct column */
    nav {
      -ms-grid-column: 1;
      grid-column: 1;
    }
    
    main {
      -ms-grid-column: 2;
      grid-column: 2;
    }
    
    aside {
      -ms-grid-column: 3;
      grid-column: 3;
    }
    

提交回复
热议问题