Skip to content

Instantly share code, notes, and snippets.

@seagalputra
Created June 5, 2020 04:53
Show Gist options
  • Save seagalputra/322ea8c5c5d5c01eda90d7ccad6cae6a to your computer and use it in GitHub Desktop.
Save seagalputra/322ea8c5c5d5c01eda90d7ccad6cae6a to your computer and use it in GitHub Desktop.
Simple solution to create unknown item grid using flexbox
<div class="container">
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div>
.container {
display: flex;
flex-direction: row;
flex-wrap: wrap;
justify-content: space-between;
}
.container > .item {
/*
1/3 - 3 columns per row
10px - spacing between columns
*/
box-sizing: border-box;
margin: 12px 12px 0 0;
width: calc(1 / 3 * 100% - (1 - 1 / 3) * 12px);
}
/*
align last row columns to the left
3n - 3 columns per row
*/
.container > .item:nth-child(3n) {
margin-right: 0;
}
.container::after {
content: '';
flex: auto;
}
/*
remove top margin from first row
-n+3 - 3 columns per row
*/
.container > .item:nth-child(-n + 3) {
margin-top: 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment