Implementing a responsive layout that can scale between mobile and desktop devices is not easy. Some of these methods include flexbox and media queries.
What about scaling font size or content width across different viewport sizes?
You can use a neat little trick. At a given viewport width, we want a certain output size. At another given viewport with, we want another output. In order to figure out the CSS equation, we will use some math.
For example, when the viewport is 320px, we want to have a width of 86vw. When the viewport is 1440px, we want a width of 70vw.
The Math
To make the math work, the input and output values will be pixels. From here on, if a unit is not given, it's in pixels
Set up the equation as a function, :
Create a line between these two points: Substitute into point-slope form:
In order for this equation to be responsive, we need to get rid of .
Since represents the entire screen, we can multiply the coefficient by 100,
to get rid of . This causes to be in . The constant term remains unchanged, and is still in pixels.
The resulting equation:
You can put this equation into calc
in CSS
.content {
width: calc(65.4285714286vw + 65.828571429px);
margin: auto;
}
See this in action
The calculations above are the same formula I used to calculate the width of the main column of this page. If you open resize this page, notice how the width of this column gradually changes from 1008px at a 1440px viewport to 275.2px at a 320px viewport.
Clamp
Since we used a linear equation, if the viewport is 201px wide, then the width becomes 197.34px.
If you want to set a minimum and maximum constraint on the equation, then you can use the
clamp
function.
Quoting MDN:
The clamp() CSS function clamps a middle value within a range of values between a defined minimum bound and a maximum bound. The function takes three parameters: a minimum value, a preferred value, and a maximum allowed value.If we want the minimum width to be 275.2px, and the maximum width 1008px, the following could be used:
.content {
width: clamp(275.2px, 65.4285714286vw + 65.828571429px, 1008px);
margin: auto;
}
Calculator
The generated CSS equation. Wrap it in calc
or use clamp
!