JSFiddle - React, Tailwind, and code Playground

by r043v

CSS

/* demo colors */
.auto4 { margin-bottom:20px; width:100%; float:left; background:#cccccc; }
.auto4 > *:nth-child(odd) { background:pink; }
.auto4 > *:nth-child(even) { background:yellow; }

/* all items */
.auto4 > * { width:24.35%; margin-left:0.5%; float:left; } /* width : (100% - (margin*(nb+1))) / nb => (100% / (margin*5)) / 4 => (100 - 2.5) / 4 */

/* all no 4 multiples */
.auto4 > *:first-child:nth-last-child(3), .auto4 > *:first-child:nth-last-child(4n+3) ~ *:nth-last-child(-n+3), /* 1*3 */
.auto4 > *:first-child:nth-last-child(6), .auto4 > *:first-child:nth-last-child(4n+6) ~ *:nth-last-child(-n+6), /* 2*3 */
.auto4 > *:first-child:nth-last-child(9), .auto4 > *:first-child:nth-last-child(4n+9) ~ *:nth-last-child(-n+9)  /* 3*3 */
{ margin-left:6.25%; width:25%; clear:none; } /* no stretch, center */
/*{ width:32.66%; clear:none; }*/ /* stretch */

/* general clear */
.auto4 > *:nth-child(4n+5),
.auto4 > *:first-child:nth-last-child(4n+3) ~ *:nth-last-child(-3n+3),
.auto4 > *:first-child:nth-last-child(4n+6) ~ *:nth-last-child(-3n+6),
.auto4 > *:first-child:nth-last-child(4n+9) ~ *:nth-last-child(-3n+9)
{ clear:left; }

/* particular cases */
.auto4 > *:first-child:nth-last-child(1){ width:99%; } /* 1*1 */
.auto4 > *:first-child:nth-last-child(2),.auto4 > *:first-child:nth-last-child(2) ~ * { width:49.25%; } /* 1*2 */

/* 5 items case */
.auto4 > *:first-child:nth-last-child(5) ~ * { clear:none; } /* no clear please */
.auto4 > *:first-child:nth-last-child(5) ~ *:nth-child(4) { clear:left; }
.auto4 > *:first-child:nth-last-child(5), .auto4 > *:first-child:nth-last-child(5) ~ *:nth-child(-n+3){ width:32.66%; } /* 3 first of 1*3 + 1*2 */
.auto4 > *:first-child:nth-last-child(5) ~ *:nth-child(n+4){ width:49.25%; } /* 2 last of 1*3 + 1*2 */

JavaScript

var $body = $("body");

function articles(byline,min,max)
{   var cls = "auto"+byline;
    for(a=min;a<=max;a++)
    {    var $a = $("<article/>").addClass(cls);
         for(n=1;n<=a;n++)
         {   /*if(Math.round(Math.random()*4) === 1)
                  $a.append("<p>"+n+"<br>"+n+"</p>");
             else*/ $a.append("<span>"+n+"</span>");
         }
         $body.append($a);
    }
}

articles(4,1,60);
/*
function onlyFirst(prefix,nb,nbchild,rulez)
{   var o = "";
    if(nbchild !== 0)
    {   o += prefix+":first-child:nth-last-child("+nbchild+")";
        if(nb === nbchild)
        o += ","+prefix+":first-child:nth-last-child("+nbchild+") ~ *" ;
        else {
            o += ","+prefix+":first-child:nth-last-child("+nbchild+") ~ *:nth-child(-n+"+nb+")" ;
        }
     
    } else o += prefix+":nth-child(-n+"+nb+")";

    if(rulez !== undefined)
        o += "{ "+rulez+" }";
    return o;
}

$body.append( onlyFirst(".auto4 > *",1,1,"width:99%;")+"<br>" );
$body.append( onlyFirst(".auto4 > *",2,2,"width:49.25%;")+"<br>" );

$body.append( onlyFirst(".auto4 > *",3,5,"width:32.66%;")+"<br>" );
*/