Search code examples
csssassflexboxstylus

How to get 2 or 3 colours pattern with flex responsive grid of squares (2,3 or 4 in row)? Stylus / SASS


Not easy to get good title, but to explain:

I have flex grid of squares. I would prefer to stick to only 2 colors for them. It is not an issue when I have 2 or 4 in line (small or large screens), but it becomes the issue on middle size screens where I have 3 squares in the row.

To give example: c1 color1, c2 color 2

Small screen:

c1 c2

c2 c1

c1 c2 ...

Similar pattern on large screens but with 4 in the row:

c1 c2 c1 c2

c2 c1 c2 c1 ...

On medium screens I need to have it this way:

c1 c2 c1

c2 c1 c2

c1 c2 c1 ...

If possible I would prefer to get automatically with CSS by SASS/Stylus ( I am using stylus but it is SASS inspired so sass solution will work.

If someone could advise how to handle it with 4 colours would be great.

So far I have no idea how to start with that because of the fact that it is all in one flex row with wrap so no idea how to determine if it is odd/even element (not to try to think about 3 colours...)


Solution

  • I made you a sasssouce. Add in selectors, colors and breakpoints. Serve hot.

    <colors>
      <color></color>
      <color></color>
      <color></color> 
      ...
    </colors>
    
    $c1 : #f50;
    $c2 : #fc0; 
    $sm : 480px;
    $md : 768px;
    $lg : 992px;
    $parent: 'colors';
    $child: 'color';
    
    #{$child} {
      background-color: $c1;
    }
    #{$child}:nth-child(2n + 1) {
      background-color: $c2;
    }
    @media (min-width: $sm) and (max-width: $md) {
      #{$child}:nth-child(4n+2),
      #{$child}:nth-child(4n+3) {
        background-color: $c1
      }
      #{$child}:nth-child(4n),
      #{$child}:nth-child(4n+1) {
        background-color: $c2
      }
    }
    @media (min-width: $lg) {
      #{$child}:nth-child(8n+5),
      #{$child}:nth-child(8n+7) {
        background-color: $c1;
      }
      #{$child}:nth-child(8n+6),
      #{$child}:nth-child(8n+8) {
        background-color: $c2;
      }
    }
    
    /* 
     * rest is layout - might want to ignore it 
     * necessary for fiddle to function 
     */
    
    #{$parent} {
      display: flex;
      flex-wrap: wrap;
    }
    #{$child} {
      min-height: 6rem;
      flex: 0 0 100%;
      display: block;
    }
    @media (min-width: $sm) and (max-width: $md) {
      #{$child} {
        flex: 0 0 50%;
      }
    }
    @media (min-width: $md) {
      #{$child} {
        flex: 0 0 33.3333%;
      }
    }
    @media (min-width: $lg) {
      #{$child} {
        flex: 0 0 25%;
      }
    }