Search code examples
htmlcsscss-grid

How to make items in a grid fit in one row?


I'm trying make 3 divs fit inside a grid. However I'd like to reuse the code for other grids where there can be more than one grid. Is this possible or should I write the code separately?

  <div class="div-wrapper">
    <div class="div1"></div>
    <div class="div2"></div>
    <div class="div3"></div>
  </div>

.div-wrapper{
  display:grid;
  grid-template-columns:repeat(3,1fr);
  grid-gap:5px;
  width:100%;
  height:10vh;
  background:black;
}

However, I'd like to use the above code other wrappers with more than 3 divs inside such as

    <div class="div-wrapper">
      <div class="div1"></div>
      <div class="div2"></div>
      <div class="div3"></div>
      <div class="div4"></div>
      <div class="div5"></div>
    </div>

Solution

  • Then don't say you have 3 columns.

    You can just use grid-auto-flow like this:

    .div-wrapper {
      display: grid;
      grid-auto-flow: column;
      grid-gap: 5px;
      width: 100%;
      height: 10vh;
    }
    

    Then it will behave like flex and you can have auto number of columns.