2

I have 2 layouts I want to use for a CSS grid depending on if there is enough width to display the items without them being too squeezed.

Each coloured block should take the space it needs to display its content without wrapping.

If the display is too narrow then each of the coloured blocks would stack veritcally and take the full width.

I've tried a number of solutions but can't figure this out.

Can anyone help me achieve this please? Thanks!

NB. please ignore the stretched text the pics are just for layout

wide layout

narrow layout

Codepen

.container {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(100px, 1fr));
  text-align: center;
}

.grid>div:first-child {
  grid-column: span 8;
}

.firstItem {
  background: yellow;
}

.option {
  height: 100%;
  min-height: 90px;
}

.secondItem {
  display: grid;
  grid-auto-flow: column;
}

.optionsContainer {
  background-color: grey;
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
}

.check {
  background-color: pink;
}
<div class='container'>
  <div class='firstItem'>
    I am the first item</div>
  <div class='secondItem'>
    <div class='optionsContainer'>
      <div class='option'>
        option 1
      </div>
      <div class='option'>
        option 2
      </div>
      <div class='option'>
        option 3
      </div>
    </div>
    <div class='check'>
      <input type='checkbox' />
      <label>I am the checkbox</label>
    </div>
  </div>
</div>
Alistair Colling
  • 1,363
  • 2
  • 19
  • 29
  • 1
    This seems like a flexbox use case rather than CSS grid. – Thammarith Sep 06 '21 at 14:57
  • thanks @Thammarith this does work in flexbox. However, I think CSS grid should be perfect for this as it operates on 2 axes and can auto-layout items depending on available space. Flexbox only works on one axis so we would need more markup – Alistair Colling Sep 06 '21 at 15:02
  • 1
    How do you define "too squeezed"? If it's a set width then a media query is a simple solution. – DBS Sep 06 '21 at 15:04
  • 1
    Hi, too squeezed in this context means: 1. No wrapping of text 2. All padding remains. If the width of the items and their padding is smaller than the available width then we wrap – Alistair Colling Sep 06 '21 at 15:19
  • Perhaps a simple "float: left; width: 33%" would do the job. If there is enough space the items will appear on one row, otherwise would go down. Or maybe you need them 100% of width if the blocks go down? If so, then you need media query plus flex or float:left. – Azu Sep 06 '21 at 19:05
  • https://stackoverflow.com/q/65782044/8620333 – Temani Afif Sep 06 '21 at 20:01

0 Answers0