Search code examples
cssflexboxcss-grid

Using CSS Grid and getting specifically content to fit


I am trying to use grid-template-columns: auto auto min-content auto; But I am not getting it to work properly. I would like the content in the yellow block to fit exactly the content present. This content will be variable and may change. However when i run the following code. It breaks the content into the second line when I just want it to fill everything in the first line. So in this case October will be in the first line and 25 comes below. I would like it to be on the same line, bearing in mind that this content will be variable.

.box {
  color: #FFF;
  font-family: sans-serif;
}

.box--green {
  background-color: #3D9970;
}

.box--blue {
  background-color: #0074D9;
}

.box--yellow {
  background-color: #FFDC00;
}

.box--red {
  background-color: #FF4136;
}


/* 
     * position your boxes wherever you want in your grid
     */

.swimmeet-meta {
  display: grid;
  grid-template-columns: 30px 30px fit-content auto;
  grid-template-rows: repeat(2, 1fr);
  /* 2 rows */
}

.swimmeet-meta__item--play {
  grid-area: 1 / 1 / 3 / 3;
}

.swimmeet-meta__item--title {
  grid-area: 1 / 3 / 2 / 5;
  grid-column-start: 3;
  grid-column-end: 5;
}

.swimmeet-meta__item--date {
  grid-area: 2 / 3 / 3 / 4;
}

.swimmeet-meta__item--time {
  grid-area: 2 / 4 / 3 / 5;
}
<main class="swimmeet-meta">
  <div class="box swimmeet-meta__item--play box--green">Book</div>
  <div class="box swimmeet-meta__item--title box--blue">Join swim meeting soon daily</div>
  <div class="box swimmeet--meta__item--date box--yellow">October 26</div>
  <div class="box swimmeet--meta__item--time box--red">1 hour</div>
</main>


Solution

  • adjust your template to be grid-template-columns: 30px 30px auto 1fr; and simplify your code like below:

    .box {
      color: #FFF;
      font-family: sans-serif;
    }
    
    .box--green {
      background-color: #3D9970;
    }
    
    .box--blue {
      background-color: #0074D9;
    }
    
    .box--yellow {
      background-color: #FFDC00;
    }
    
    .box--red {
      background-color: #FF4136;
    }
    .swimmeet-meta {
      display: grid;
      grid-template-columns: 30px 30px auto 1fr;
      grid-template-rows: repeat(2, 1fr);
    }
    
    .swimmeet-meta__item--play {
      grid-area: span 2/span 2;
    }
    
    .swimmeet-meta__item--title {
      grid-column: span 2;
    }
    <main class="swimmeet-meta">
      <div class="box swimmeet-meta__item--play box--green">Book</div>
      <div class="box swimmeet-meta__item--title box--blue">Join swim meeting soon daily</div>
      <div class="box swimmeet--meta__item--date box--yellow">October 26</div>
      <div class="box swimmeet--meta__item--time box--red">1 hour</div>
    </main>