CSS CSS Flexbox Layout Building a Layout with Flexbox Creating a Three Column Layout with Flexbox

Can calc be used for a flex basis value?

Is it possible to use the calc function within a flex-basis value?

For example if I have a flex item set to flex: 1 25% could I use it to set some spacing;

Please let me know, :)

Can you be more specific on what you're trying to do and how you would want to use calc()?

Basically I have a grid of flex items, to which I assigned flex: 1 25%, so that the item occupies 1/4th of the screen's width, now however I'd like to have some space in between the flex items, hence why I asked whether it would be possible with the calc function...

2 Answers

Shawn Denham
PRO
Shawn Denham
Pro Student 16,787 Points

That is a great question!

With that said I don't know. You could try something like codepen to test it out and let us know!

Unless you're trying to achieve a fixed pixel gap between the items you probably don't need calc().

With calc() you can do something like calc(25% - 10px) and this would give you a fixed number of pixels between each item. If you just want to have a flexible percentage based gap then you probably want to lower the 25% to something like 23% as an example. The size of the gap will change based on container width.

However, since you have flex-grow set to 1 the items are going to grow to 25%. If you do flex: 1 23% they will still be 25% because they will each get an equal amount of the remaining space.

You likely want to either set flex-basis on its own or just set a width on the flex items.

Examples:

.flex-items {
  flex-basis: 23%;
}
/* or */
.flex-items {
  flex-basis: calc(25% - 15px);
}
/* or */
.flex-items {
  width: 23%;
}
/* or */
.flex-items {
  width: calc(25% - 15px);
}

And then probably something like justify-content: space-between on the flex container.