Skip to content

Instantly share code, notes, and snippets.

@f0-x
Created March 15, 2024 04:26
Show Gist options
  • Save f0-x/ade0625dd5bbf58a06cc2be6453ec0ea to your computer and use it in GitHub Desktop.
Save f0-x/ade0625dd5bbf58a06cc2be6453ec0ea to your computer and use it in GitHub Desktop.
Flexbox 1-liner with `calc` & Custom Props
/*🎉 The formula:
calc((100% / var(--columns)) - var(--gap) + (var(--gap) / var(--columns)));
*/
.parent {
--gap: 20px;
--columns: 4;
display: flex;
gap: var(--gap);
flex-wrap: wrap;
}
.child {
flex: 0 1 calc((100% / var(--columns)) - var(--gap) + (var(--gap) / var(--columns)));
}
/*
• Get 100% of the width and divide it by the number of columns, eg: 2 is 50%, 3 is 33.33%, 4 is 25%, etc
• Then it subtracts the gap, so 50% — 20px, 33.33% — 20px, 25% — 20px, etc.
• Then it takes the gap, and divides it by the number of columns. So, 20px / 2 for 10px, 20px / 3 for 6.667px, 20px / 4 for 5px, etc
• Then it add that to the subtracted number, like so:
*/
/*example: 2 columns with 20px gap*/
calc((100% / 2) - 20px + (20px / 2));
calc(50% - 20px + 10px);
calc(50% - 10px);
/*example: 3 columns with 20px gap*/
calc((100% / 3) - 20px + (20px / 3));
calc(33.33% - 20px + 6.667px);
calc(33.33% - 13.33px);
/*example: 4 columns with 20px gap*/
calc((100% / 4) - 20px + (20px / 4));
calc(25% - 20px + 5px);
calc(25% - 15px);
/*example: 5 columns with 20px gap*/
calc((100% / 5) - 20px + (20px / 5));
calc(20% - 20px + 4px);
calc(20% - 16px);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment