Search code examples
cssflexboxcss-grid

CSS Grid: How do I put everything on a single row?


I am trying to use grid more, but I can’t work out what should be a simple question. How do I put all of the elements in a single row?

That is, I want to emulate the flex layout for a single row.

I know I can use grid-template-columns: 1fr 1fr 1fr 1fr; in the example below, but I don’t want to set a specific number of columns.

div#flex {
  display: flex;
  flex-direction: row; /* I know that’s not necessary */
}
div#flex>button {
  flex: 1;
}

div#grid {
  display: grid;
  grid-template-rows: 1fr;
}
div#grid>button {

}
<div id="flex">
  <button>One</button>
  <button>Two</button>
  <button>Three</button>
  <button>Four</button>
</div>

<div id="grid">
  <button>One</button>
  <button>Two</button>
  <button>Three</button>
  <button>Four</button>
</div>


Solution

  • You can just add grid-auto-flow: column; instead : https://stackblitz.com/edit/angular-9midxc

    div#flex {
      display: flex;
      flex-direction: row;
      /* I know that’s not necessary */
    }
    
    div#flex>button {
      flex: 1;
    }
    
    div#grid {
      display: grid;
      grid-auto-flow: column;
    }
    
    div#grid>button {}
    <div id="flex">
      <button>One</button>
      <button>Two</button>
      <button>Three</button>
      <button>Four</button>
    </div>
    
    <div id="grid">
      <button>One</button>
      <button>Two</button>
      <button>Three</button>
      <button>Four</button>
    </div>