I want to create a modular interface with three columns, all three of which should basically have the same width, with a divider between each.
If you then hold down the divider and drag to the left or right, the surrounding two columns should increase/decrease in width respectively, but not the last element, that should remain unchanged.
What approach should I try? Thanks in advance!
Here are some visualizations of my plans:
When you drag & drop the divider between the purple and blue field:
I've tried it so far with flex: 1;
and then always changing the flex-basis, but this affects the width of all three elements, not just the two surrounding ones.
If I'm using width
for resizing, the mechanics of adjusting columns widths works, but the default view doesn't work because I don't know how to evenly distribute the width across all elements.
You're starting with each column having flex: 1, giving your container a total of flex 3 space. Remember this for later.
Flex values
Going further, if each columns starts with equal widths, then each starts with 0.3333333333 width out of 1. Let's focus on the widths without flex.
Width percentages:
If you want to change box widths two at a time, try changing each of the 3 box's flex values individually (e.g., using document.querySelector()
and setting purpleBox.style.flex = '0.1'
). That way, the proportions will remain correct even if you resize the whole container. The main thing you have to understand is that each box's width is a function of the percentage position of the dividers relative the whole container. So if the first divider is 25% from the left of the container, then the purple box must 25% (0.25) of the width. If the second divider is 80% from the left, then the green box must be 20% (0.2) of the width (i.e., 1 - 0.8). Finally, the blue box must be 55% (or 0.55) of the width (i.e., 0.8 - 0.25).
New width percentages
Finally, if we tie the flex values back into it, we know that the total container has flex 3, so the final flex values (in order of purple, blue, green) would be their percentage widths multiplied by 3.
New flex values
(notice how 0.75 + 1.95 + 0.60 adds up to the total 3 flex of the container?)
Hopefully that helps you get started. Essentially, whenever you drag a divider, you need to run that computation (purple = left divider percent, blue = right divider percent minus left divider percent, green = 1 minus right divider percent) and then set each box's flex value accordingly.