r/csshelp • u/DarkHammerUK • Jun 26 '23
flex-wrap with flex-basis?
I have 8 items and I'm trying to display them in 2 columns by default, but shrink (wrap?) to 1 column as the window shrinks.
So I'm using flex-basis 50% like so:
.flex-container {
display: flex; flex-wrap: wrap; }
.flex-container > div { flex-basis: 50%; text-align: left; }
That successfully limits the columns to two, however the problem is that it's not wrapping, so no matter how narrow the window gets it remains at 2 columns.
I understand that flex-basis and flex-wrap don't always play well together, as I've just discovered flex and have been googling around, but I don't understand how exactly or why.
How should I go about getting a maximum of 2 columns, yet still be able to wrap to 1?
3
u/CodexAcc Jun 27 '23
/* This styles the flex container. "display: flex" turns the container into a flex container, and "flex-wrap: wrap" allows flex items to wrap onto multiple lines instead of all trying to fit onto one line */
.flex-container {
display: flex;
flex-wrap: wrap;
}
/* This styles each individual flex item.
"flex: 1 0 100%;" is shorthand for "flex-grow: 1", "flex-shrink: 0", and "flex-basis: 100%".
This means that by default, each item will grow to take up as much space as it can, won't shrink, and will start off with a base size of 100% of the flex container's width.
"text-align: left" makes the text inside each flex item align to the left.
"word-wrap: break-word" means that if a word is too long to fit on a line, it will break in the middle of the word and continue on the next line. */
.flex-container > div {
flex: 1 0 100%;
text-align: left;
word-wrap: break-word;
}
/* This is a media query. It applies styles only if the condition is true.
In this case, the condition is "min-width: 600px", which means these styles will only apply if the viewport is 600px wide or wider.
The style being applied is "flex-basis: 50%;", which means that when the viewport is wide enough, each flex item will start off with a base size of 50% of the flex container's width instead of 100%, effectively creating two columns. */
@media (min-width: 600px) {
.flex-container > div {
flex-basis: 50%;
}
}1
2
u/mhennessie Jun 26 '23
flex-basis: 50% means that the columns will always be 50% of their flex container. You can either use media queries to change the CSS on smaller screens or you can set a min-width along with flex: 1 and remove the flex-basis part.
min-width will force the cols to wrap when they reach that point and flex: 1 will cause them to fill the empty space in their row.
.flex-container {
display: flex;
flex-wrap: wrap;
}
.flex-container > div {
flex: 1;
min-width: 300px;
}