Margin depending on screensize and variable in width

44 Views Asked by At

I want to create a variable margin on the left, depending on screensize. At 1351px screenwidth, and the margin should be 12.583vw, when the screen is 2250px wide, the margin should be 29.802vw.

How can I do this correctly? I am new to the min/max/clamp. I probable need to use some sort of calculation, but I do not know how. Please advice.

margin-left: min(29.802vw, 12.583vw)

1

There are 1 best solutions below

1
schenney On

Would you like the margin to vary continuously as the viewport width changes, or behave discretely?

That is ... a margin of 12.583vw for all widths up to 2250px, and then 29.802vw for widths greater than 2250px, or a margin that increases smoothly super-linearly as the screen width increases.

The former would be done with media queries:

@media (width >= 2250px) {
  div { margin-left: 29.802vw; }
}
@media (width < 2250px) {
  div { margin-left: 12.583vw; }
}

The latter would indeed be some form of calc():

body { margin: calc([some function]vw); }

Appended in response to the comment: Short answer: You'll need to use Javascript to compute and update the margin.

Long answer: Lets assume you want to linearly interpolate the 2 specific margin/width pairs you've given. We need the slope and intercept of the line that relates margin to screen size. That is, a and b in margin = a * width + b.

You have 2 equations for the number of vw you want for the margin:

12.583 = a * 1351 + b
29.80 = a * 2250 + b

Subtract the first from the second to get a alone, and re-organize:

29.802 - 12.583 = a * (2250 - 1351)
a = 0.01915

Substitute a into one of the original equations and get

b = 13.284

So the calc you would like is: calc(((100vw * 0.01915) - 13.284px) * 1vw); That computes the coefficient you need and then multiplies it by 1vw to get a quantity in vw. But this is not valid, because the coefficient itself has units px, and you can't multiply px by vw in calc.

The solution is to strip the units, but you can't in CSS (see Is there a way to remove units from a calc function in CSS)

The javascript looks like this:

<style>
  div {
    background-color: red;
    height: 100;
    width: 50vw;
  }
</style>
<body>
   <div id="main">
   </div>
   <script>

  function setMargin() {
    let vw = Math.max(document.documentElement.clientWidth || 0, window.innerWidth || 0);
    coefficient = vw * 0.01915 - 13.284;
    main.style.marginLeft = coefficient.toString() + "vw";
  }

  setMargin();

  window.onresize = setMargin;
</script>
</body>