https://www.reddit.com/r/csshelp/comments/1i49o0u/how_does_one_achieve_perfectly_responsive_gap/
created by Popular-Light-3457 on 18/01/2025 at 15:17 UTC*
2 upvotes, 1 top-level comments (showing 1)
i have a flex container with 3 child elements. Currently they have a fixed gap of 1em. I want the child elements to get closer together (decrease their gap) as the containers width decreases.
I want the gap to go all the way to 0 to avoid wrapping for as long as possible.
I know i can use clamp and vw to kind of achieve this: clamp(0em 1vw, 1em).
This will set the gap based on 1% of the viewports width (with an upper & lower bound), the problem with that however is that it only goes to 0 once the windows viewports width approaches 0, which isn't actually what i want. I want it to go to 0 as the viewports width approaches the width of the parent container.
So, in other words, that the gap goes to 0 once the width of the container takes up the full width of the current viewports width.
Can i achieve this without javascript?
Comment by be_my_plaything at 18/01/2025 at 16:15 UTC
3 upvotes, 0 direct replies
Something like:
gap: min(60px, max(calc(5vw - 30px), 0px));
Should do it, although it will take some calculations or trial and error to get the values as you want them.
The outer part, the `min()` chooses the smallest value from the options, in this case either `60px` or the `max()` value with the `calc()` so if the `calc()` gives a large result the `60px` (Or whatever value you want) takes over and stops the gap getting to big.
At the lower end, the `max()` option takes over (as it becomes smaller than the 60px) this takes the larger of the two options, in this case either the `calc()` or zero. So basically as soon as the `calc()` gives a negative result zero is selected (as the larger option) and you get no gap. The `calc()` subtracts a fixed width from a vw width, so when the screen shrinks and vw becomes smaller it reaches a point where the fixed amount you're subtracting is greater than the vw long before the screen would make the vw value zero... So you can select a point to jump to zero.
So if the example I gave you need 5vw to be less then 30px for it to select the zero gap. So 1vw must be less than 6px. On a 600px screen 1vw equals 6px, so any smaller than a 600px screen and the gap becomes zero.
https://codepen.io/NeilSchulz/pen/LEPBQej[1] < Kinda like this!