jon thompson

CSS Flex Grid

Posted on 2019-05-02 12:18:36
Create a quick and easy grid using only CSS with FlexBox

Example HTML

<div>
<div>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean scelerisque massa et ligula suscipit mattis. Integer consectetur urna vitae interdum blandit. Phasellus aliquet ligula libero, nec pretium diam dictum quis. Nullam viverra sem a nibh tempor venenatis. Suspendisse congue rhoncus tortor non placerat. Fusce posuere velit risus. Maecenas volutpat rutrum lorem. Nam ut pharetra sem, tincidunt lobortis nibh. Donec sit amet nisl tempor, maximus orci at, cursus felis. Maecenas sodales auctor nulla ac pulvinar.</p>
</div>
<div>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean scelerisque massa et ligula suscipit mattis. Integer consectetur urna vitae interdum blandit. Phasellus aliquet ligula libero, nec pretium diam dictum quis. Nullam viverra sem a nibh tempor venenatis. Suspendisse congue rhoncus tortor non placerat. Fusce posuere velit risus. Maecenas volutpat rutrum lorem. Nam ut pharetra sem, tincidunt lobortis nibh. Donec sit amet nisl tempor, maximus orci at, cursus felis. Maecenas sodales auctor nulla ac pulvinar.</p>
</div>
</div>

The CSS

:root {
--gutter-width: 2.0em;
}

div[class^="flex-grid"] { display: block!important; }

div[class^="flex-grid"] .col {
width: 100%!important;
margin: 0 0 var(--gutter-width) 0!important;
}

@media (min-width: 400px) {
div[class^="flex-grid-"] {
display: flex;
justify-content: space-between;
margin-bottom: var(--gutter-width);
}

div[class^="flex-grid-"] .col {

}

.flex-grid-1 .col {
width: 100%;
}

.flex-grid-2 .col {
width: calc((100% - (var(--gutter-width) * 1)) / 2);
}

.flex-grid-3 .col {
width: calc((100% - (var(--gutter-width) * 2)) / 3);
}

.flex-grid-4 .col {
width: calc((100% - (var(--gutter-width) * 3)) / 4);
}

.flex-grid-5 .col {
width: calc((100% - (var(--gutter-width) * 4)) / 5);
}

.flex-grid-6 .col {
width: calc((100% - (var(--gutter-width) * 5)) / 6);
}
}