<div class="container">
  
  <input type="number" value="4" />

  <ul></ul>
  
</div>
*,
*::before,
*::after {
  box-sizing: border-box;
}

body {
  margin: 0;
  min-height: 100vh;
  padding: 0;
}

input {
  border: 2px solid;
  color: #333;
  font-size: 1.5rem;
  margin: 1rem 0;
  padding: .5em;
}

input,
li {
  border-radius: 6px;
}

.container {
  margin: 0 auto;
  max-width: 1280px;
  width: 90%;
}

$rect-margin: 1rem;

ul {
  display: flex;
  flex-wrap: wrap;
  list-style: none;
  margin: -$rect-margin;
  padding: 0;
}

li {
  background-color: tomato;
  flex-basis: calc(33.3333% -  #{2 * $rect-margin});
  flex-grow: 1;
  flex-shrink: 0;
  height: 150px;  
  margin: $rect-margin;
  min-width: 290px;
  
  &:nth-last-child(4n):first-child ~ li, 
  &:nth-last-child(4n):first-child, 
  &:nth-last-child(7n):not(:nth-last-child(14n)):first-child ~ li, 
  &:nth-last-child(7n):not(:nth-last-child(14n)):first-child {
    flex-basis: calc(25% - #{2 * $rect-margin});    
  }  
}
View Compiled
const numberInput = document.querySelector('input');
renderRects(numberInput.value);

numberInput.onchange = event => {
  renderRects(event.currentTarget.value);
} 

function renderRects(numberOfRects) {
  const ul = document.querySelector('ul');
  
  Array.from(ul.children).forEach(li => ul.removeChild(li));
  
  for (let i = 0; i < numberOfRects; i++) {
    const li = document.createElement('li');
    ul.appendChild(li);
  }
}

View Compiled

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

This Pen doesn't use any external JavaScript resources.