19
loading...
This website collects cookies to deliver better user experience
The following snippet is a powerful set of CSS rules I use all the time. I think it solves a common layout issue I want to help others solve.
Table of Contents |
---|
The Problem |
The Solution |
The Explanation |
The overflow elements - Depending on the size of our page and the size of the elements in our list, we can have a variable number of items that "overflow" at the end of the list. How do we tackle this? Do we want them to be right justified? Do we want to hardcode some styles for each situation: if 1 item, width 100%, if 2 items width 50%, etc etc?
The size & spacing of the items - How much tweaking do we want to do to ensure the items look good? Are we okay with a max-width
or do we need a min-width
for the item to look okay? Are we using all the white space? Are things centered or is everything left-aligned?
Is IE friendly.
.flex {
--gap: 15px;
display: inline-flex;
flex-wrap: wrap;
flex-direction: row;
margin: calc(-1 * var(--gap)) 0 0 calc(-1 * var(--gap));
width: calc(100% + var(--gap));
}
.flex > * {
flex-grow: 1;
flex-shrink: 1;
flex-basis: 225px;
margin: var(--gap) 0 0 var(--gap);
}
margin
, the calc
function, and flexbox's flex-grow
and flex-basis
properties.top
and left
margin to all the children elements..flex
container in the opposite direction of our top and left margins we added on the children.gap
property, but this currently has limited support in some mobile browsers and all of IE.flex-grow: 1;
. This tells the parent "Hey for all the children you have, make sure they take up ALL of the white space available".flex-grow: 1;
flex-basis
as our "default" size, and then with flex-grow
, if we have less items on the last line, they will fill up the remaining space and look nice. .flex {
--gap: 15px;
display: inline-flex;
flex-wrap: wrap;
flex-direction: row;
/* */
margin-top: calc(-1 * var(--gap));
margin-right: 0;
margin-bottom: 0;
margin-left: calc(-1 * var(--gap));
width: calc(100% + var(--gap));
}
.flex > * {
flex-grow: 1;
flex-shrink: 1;
flex-basis: 225px;
margin-top: var(--gap);
margin-right: 0;
margin-bottom: 0;
margin-left: var(--gap);
}