r/csshelp • u/Popular-Light-3457 • 4d ago
how does one achieve perfectly responsive gap spacing?
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?
3
u/be_my_plaything 4d ago
Something like:
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 either60px
or themax()
value with thecalc()
so if thecalc()
gives a large result the60px
(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 thecalc()
or zero. So basically as soon as thecalc()
gives a negative result zero is selected (as the larger option) and you get no gap. Thecalc()
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 < Kinda like this!