I’m trying to set the width of the striped area in my drawing below, so that it falls within the bounds of the site content. The width of the content is 80%, with a maximum width of 1080px, and centered (illustrated below in purple). The columns are variable widths, but together always fill the width of the page – I used 75%/25% below for argument’s sake.
What is the algorithm to achieve this? I have tried I number of things, including:
width: calc(80vw / <column width>)
but that’s way off. I want the CSS width assignment to work for any column size (I’m using hubl to create a for loop in the CSS – so I am able to use variables.. similar to SCSS)
2
Answers
Say the container’s width is always 100% (or rather 100vw), in that case
would suffice. But, since the container’s width is limited to a
max-width
(of1080px
), keeping the striped element width at 25vw would make it too large – as we incremented the viewport width.Therefore the question is:
Setting the striped element’s width to 25vw and slowly resizing the viewport the answer would become immediately visible and obvious:
Solution:
Example:
Tip:
if you cannot use
body
but you have another parent which width does not match 100vw, then usecontainer-type: size;
on that element, and changevw
units from the above code intocqw
(container-query units) – and will work the same.There are two scenarios we need to include in the calculation.
The screenshot below illustrates the setup:
So for scenario 1, the width of the striped area is the width of the red area minus the width of the white area underneath the red area. To get the width of the white area we subtract the width of the lime area from the viewport width, then divide by two (because there are white areas on both sides). The equation for this scenario is therefore:
For scenario 2 it’s simpler, because we know that the white area is simply 10vw, so the equation for this scenario is:
For the overall equation we just need to take whichever of these two results has the smaller value. The CSS representation of the equation uses both
min()
andcalc()
:Here is a working snippet to demonstrate:
After running this snippet, use the full page link to test the responsive behaviour.