I have a fluid width container DIV.
Within this I have 4 DIVs all 300px x 250px...
-
Other posts have mentioned flexbox, but if more than one row of items is necessary, flexbox's space-between
property fails (see the end of the post)
To date, the only clean solution for this is with the
CSS Grid Layout Module (Codepen demo)
Basically the relevant code necessary boils down to this:
ul {
display: grid; /* (1) */
grid-template-columns: repeat(auto-fit, 120px); /* (2) */
grid-gap: 1rem; /* (3) */
justify-content: space-between; /* (4) */
align-content: flex-start; /* (5) */
}
1) Make the container element a grid container
2) Set the grid with an 'auto' amount of columns - as necessary. This is done for responsive layouts. The width of each column will be 120px. (Note the use of auto-fit
(as apposed to auto-fill
) which (for a 1-row layout) collapses empty tracks to 0 - allowing the items to expand to take up the remaining space. (check out this demo to see what I'm talking about) ).
3) Set gaps/gutters for the grid rows and columns - here, since want a 'space-between' layout - the gap will actually be a minimum gap because it will grow as necessary.
4) and 5) - Similar to flexbox.
body {
margin: 0;
}
ul {
display: grid;
grid-template-columns: repeat(auto-fit, 120px);
grid-gap: 1rem;
justify-content: space-between;
align-content: flex-start;
/* boring properties: */
list-style: none;
width: 90vw;
height: 90vh;
margin: 2vh auto;
border: 5px solid green;
padding: 0;
overflow: auto;
}
li {
background: tomato;
height: 120px;
}
Codepen demo (Resize to see the effect)
Browser Support - Caniuse
Currently supported by Chrome (Blink), Firefox, Safari and Edge! ... with partial support from IE (See this post by Rachel Andrew)
NB:
Flexbox's space-between
property works great for one row of items, but when applied to a flex container which wraps it's items - (with flex-wrap: wrap
) - fails, because you have no control over the alignment of the last row of items;
the last row will always be justified (usually not what you want)
To demonstrate:
body {
margin: 0;
}
ul {
display: flex;
justify-content: space-between;
flex-wrap: wrap;
align-content: flex-start;
list-style: none;
width: 90vw;
height: 90vh;
margin: 2vh auto;
border: 5px solid green;
padding: 0;
overflow: auto;
}
li {
background: tomato;
width: 110px;
height: 80px;
margin-bottom: 1rem;
}
Codepen (Resize to see what i'm talking about)
Further reading on CSS grids:
- MDN
- Jen Simmons - Learn CSS grid
- A Complete Guide to CSS Grid | Codrops CSS Reference
- A Complete Guide to Grid - CSS Tricks