Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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

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.