Equal width columns in CSS Grid

后端 未结 7 1116
别跟我提以往
别跟我提以往 2020-12-25 10:27

I\'d like to have the html below showing in n equal columns whether there are two, or three, or more child elements to the row element using css grid - Flexbox makes this ea

相关标签:
7条回答
  • 2020-12-25 10:47

    This allows the columns to distribute better, and the columns are the same size regardless of whether the size of the items does not adjust.

    .row {
      display: grid;
      grid-template-columns: repeat( auto-fit, minmax(33.33%, 1fr) );
    }
    .item {
      grid-column: span 1;
    }
    
    0 讨论(0)
  • 2020-12-25 10:56

    @Michael_B's answer is almost there.

    .grid-container {
       display: grid;
       grid-auto-columns: 1fr;
       grid-auto-flow: column;
    }
    

    Gives you one row of equally sized columns in Chrome, Firefox, and Safari as of writing.

    0 讨论(0)
  • 2020-12-25 10:57

    Here is simple answer(at least in my perspective). I got this issue above answers not helped me. Here the code to divide 'div' into equal width and with required number of columns.

    //CSS
    
    .grid-container {
      display: grid;
      grid-template-columns: auto auto auto; // no of 'auto's will be number of columns here it's 3
    }
    
    //HTML
    <div class="grid-container">
        <div></div>
        <div></div>
        <div></div>
    </div>
    
    

    more info on grid can be seen here W3Schools

    0 讨论(0)
  • 2020-12-25 11:02

    Define this on your grid container. Sets up three columns of equal width.

    grid-template-columns: repeat(3, 1fr);
    
    0 讨论(0)
  • 2020-12-25 11:07

    Try this:

    .grid-container {
       display: grid;
       grid-auto-columns: 1fr;
    }
    
    .grid-items {
       grid-row: 1;
    }
    

    Otherwise, here's a demo that may be useful: jsFiddle

    To learn about the fr unit, see these posts:

    • Does CSS Grid have a flex-grow function?
    • The difference between percentage and fr units in CSS Grid Layout
    0 讨论(0)
  • 2020-12-25 11:08

    The common answer of repeat(3, 1fr) is not quite correct.

    This is because 1fr is about the distribution of available(!) space. This breaks as soon as the content becomes bigger than the track size. By default, it does not overflow and adjust the column width accordingly. That's why not all 1fr are guaranteed to be of equal width. 1fr is actually rather just a shorthand for minmax(auto, 1fr).

    If you really need the columns to be the exact same width you should use:

    grid-template-columns: repeat(3, minmax(0, 1fr));
    

    minmax(0, 1fr) allows the grid tracks to be as small as 0 but as large as 1fr, creating columns that will stay equal. But, be aware that this will cause overflows if the content is bigger than the column or cannot be wrapped.

    Here is an example that demonstrates the difference.

    0 讨论(0)
提交回复
热议问题