0

I use css grid for adjusting columns and moving them to the new line when they won't fit. Here is the code that explains everything:

.tiles-container {
  display: grid;
  grid-gap: 6rem;
  grid-template-columns: repeat(auto-fill, minmax(min(220px, 100%), 2fr));
}

a {
  background: red;
  height: 100px;
}
<div class="tiles-container">
  <a></a>
  <a></a>
  <a></a>
  <a></a>
</div>
    grid-template-columns: repeat(auto-fill, minmax(min(220px, 100%), 2fr));

Now, what I want to avoid is moving just one (single) column to the new line. Instead, it breaks down earlier and moves 2 columns together.

To explain it more visually, this is what is acceptable:

█ █ █ █

also OK:

█ █ █

█ █

also OK:

█ █

█ █

and this is what is unacceptable:

█ █ █

I want to avoid unnecessary media queries here. Here is my code: https://jsfiddle.net/tucado/0czokyxa/3/

Piotr Ciszewski
  • 1,691
  • 4
  • 30
  • 53
  • In this case I would consider making div's with two children in each. You can add 50% width to the child elements and adjust the gaps so that they are same everywhere. Then when the screen is too small, you will have a div with 2 elements on the new line instread of 1 element – Ivan Beliakov Jan 20 '23 at 22:23
  • @IvanBeliakov, unfortunately I can't do this, as for mobile view it will be a single column with one column underneath another. I will add an extra visualisation for this to explain it better. The idea behind it is to use the same CSS in many cases. Sometimes, there are 4 columns, sometimes more. – Piotr Ciszewski Jan 20 '23 at 22:28
  • 1
    https://css-tricks.com/responsive-layouts-fewer-media-queries/ a long read but you will probably find what you need – Temani Afif Jan 20 '23 at 22:33
  • @TemaniAfif, yes, thanks a lot. This is what I meant. https://jsfiddle.net/tucado/0czokyxa/5/ – Piotr Ciszewski Jan 20 '23 at 22:43

1 Answers1

2

If someone has the same problem, here is the solution: https://jsfiddle.net/tucado/0czokyxa/5/

<div class="tiles-container">

  <a></a>
  <a></a>
  <a></a>
  <a></a>  

</div>

and CSS:

  .tiles-container {
    /* first breakpoint*/
    --w1:1200px;
    --n:6;
    /* second breakpoint*/
    --w2:800px;
    --m:4;
    /* third breakpoint*/
    --w3:400px;
    --p:2;

    display:grid;
    grid-template-columns:
      repeat(auto-fill,
        minmax(clamp(clamp(clamp(  
              100%/(var(--n) + 1) + 0.1%,
                (var(--w1) - 100%)*1000,
              100%/(var(--m) + 1) + 0.1%), 
                (var(--w2) - 100%)*1000,
              100%/(var(--p) + 1) + 0.1%), 
                (var(--w3) - 100%)*1000,
              100%), 1fr));
    gap:10px;
    border:1px solid;
    overflow:hidden;
    margin:5px;
    resize:horizontal;


  }

  .tiles-container > a {
    height:100px;
    background:red;
  }

Thanks @Temani-Afif

Piotr Ciszewski
  • 1,691
  • 4
  • 30
  • 53