Search code examples
htmlcssresponsive-designmargin

How do I make a responsive margin which grows larger for larger screen sizes?


I want a margin which will be close to 0% on small screen sizes and around 20% on large ones without using @media queries to force specific numbers for all specific screen sizes.

What I am imagining is some math equation that will turn a number like 300 (300px) to 0 (0%) and a number like 2000 (2000px) to 20 (20%)? However, I am no math genius so I am asking for your help please.

Currently I am using margin: 0 10%; which is an alright compromise, however, I still find that the margin is far to large on small screen sizes and far to small on large screen sizes

:root {
  --page-margin: 10%;
}
body {
  margin: 0;
  background-color: skyblue;
}
div {
  background-color: grey;
  height: 100vh;
  margin: 0 var(--page-margin);
}
<div></div>


Solution

  • I would use the CSS clamp() function. Set the minimum to 0 and the max to 20vw (equals 20% width of the viewport). Then calculate the average value with the max value - a certain pixel value (play around with it):

    :root {
      --page-margin: 10%;
    }
    body {
      margin: 0;
      background-color: skyblue;
    }
    div {
      background-color: grey;
      height: 100vh;
      margin: 0 clamp(0vw, 20vw - 100px ,20vw);
    }
    <div></div>