<p>Dynamically scaling CSS values based on the viewport width is hardly a new topic. You can find plenty of in-depth coverage right here on CSS-Tricks in articles like this one or this one. </p>
<p>Most of those examples, though, use relative CSS units and unitless values to achieve fluid scaling. That loses pixel perfection and usually introduces text wrapping and layout shifts once the screen goes below or above a certain threshold. </p>
<p>But what if we really do want pixel perfection? What if, let’s say, we are developing a complex real-time analytics dashboard to be viewed on large TVs at a conference room or as some PWA to be opened exclusively on mobile and tablet devices, as opposed to text-heavy blogs and news websites? Those are cases where we need more precision. </p>
<p>In other words, what if we want to scale designs uniformly? Of course, one can scale the content with CSS transforms based on the available width as covered in this article — this way, the correct ratios are preserved. </p>
<p>However, we can also achieve fluid proportional scaling UIs using pixel values in CSS. They scale appropriately based on the device screen real estate, all while preserving their pixel-perfect proportions. Further, we can still use pixel values and automatically convert them to relative CSS units if working in pixels is more comfortable or familiar. </p>
<p>Scaling our UI </p>
<p>Let’s try to implement this awesome dashboard, courtesy of Craftwork. We need to make it in such a way that it scales perfectly and preserves all the texts line counts, margins, image sizes, etc. </p>
<p>Let’s work in CSS pixel values and use SCSS for speed and convenience. So, if we are to target the title of one of these card widgets, our SCSS might look something like this: </p>
<p>.cardWidget {<br />
.cardHeading {<br />
font-size: 16px;<br />
}<br />
} </p>
<p>Nothin’ fancy. Nothing we have not seen before. Being a pixel value, this will not scale. </p>
<p>This design was created with a container that’s 1600px wide. Let’s assume that at 1600px, the ideal font size for the titles of the cards should be 16px since that’s how it’s designed. </p>
<p>Now that we have the “ideal” container width font size for this width, let’s scale our CSS pixel values accordingly using the current* viewport width: </p>
<p>/*<br />
1600px is the ideal viewport width that the UI designers who<br />
created the dashboard used when designing their Figma artboards </p>
<p> Please not we are not using pixel units here, treating it purely<br />
as a numeric value.<br />
*/<br />
–ideal-viewport-width: 1600;<br />
/*<br />
The actual width of the user device<br />
*/<br />
–current-viewport-width: 100vw; </p>
<p>.cardWidget {<br />
.cardHeading {<br />
/*<br />
16px is the ideal font size that the UI designers want for<br />
1600px viewport width. </p>
<p> Please note that we are not using pixel units here,<br />
treating it purely as a numeric value.<br />
*/<br />
–ideal-font-size: 16;<br />
/*<br />
Calculate the actual font size: </p>
<p> We take our idealFontSize and multiply it by the difference<br />
between the current viewport width and the ideal viewport width.<br />
*/<br />
font-size: calc(<br />
var(–ideal-font-size) * (var(–current-viewport-width) / var(–ideal-viewport-width)<br />
);<br />
}<br />
} </p>
<p>As you can see, we treat the ideal font size we obtained from the design as a base and multiply it by the difference between the current and ideal viewport widths. How does this look mathematically? Let’s say we are viewing this web app on a screen with the exact same width as the mockup: </p>
<p>–current-device-width: 100vw; // represents 1600px or full width of the screen<br />
–ideal-viewport-width: 1600; // notice that the ideal and current width match<br />
–ideal-font-size: 16;<br />
// this evaluates to:<br />
font-size: calc(16 * 1600px / 1600);<br />
// same as:<br />
font-size: calc(16 * 1px);<br />
// final result:<br />
font-size: 16px; </p>
<p>So, since our viewport width matches perfectly, our font-size ends being exactly 16px at the ideal viewport width of 1600px. </p>
<p>As another example, let’s say we are viewing the web app on a smaller laptop screen that’s 1366px wide. Here is the updated math: </p>
<p>font-size: calc(16 * 1366px / 1600);<br />
// same as:<br />
font-size: calc(16 * 0.85375px);<br />
// final result:<br />
font-size: 13.66px; </p>
<p>Or let’s say we are viewing this on a full high-definition display at 1920px wide: </p>
<p>font-size: calc(16 * 1920px / 1600);<br />
// same as:<br />
font-size: calc(16 * 1.2px);<br />
// final result:<br />
font-size: 19.2px; </p>
<p>You can see for yourself how even though we use pixel values as reference, we are actually able to proportionally scale our CSS values based on the difference in width between the ideal and current viewport sizes. </p>
<p>Here is a small demo I built to illustrate the technique: </p>
<p>CodePen Embed Fallback </p>
<p>Here’s a video for convienence: </p>
<p>Clamping the min and max viewport width </p>
<p>Using this current approach, the design scales to match the viewport size, no matter how big or small the viewport gets. We can prevent this with CSS clamp() which allows us to set a minimum width of 350px and maximum width of 3840px. This means that if we are to open the web app on a device with 5000px width, our layout will stay locked at 3840px: </p>
<p>–ideal-viewport-width: 1600;<br />
–current-viewport-width: 100vw;<br />
/*<br />
Set our minimum and maximum allowed layout widths:<br />
*/<br />
–min-viewport-width: 350px;<br />
–max-viewport-width: 3840px; </p>
<p>.cardWidget {<br />
.cardHeading {<br />
–ideal-font-size: 16;<br />
font-size: calc(<br />
/*<br />
The clamp() function takes three comma separated expressions<br />
as its parameter, in the order of minimum value, preferred value<br />
and maximum value:<br />
*/<br />
–clamped-viewport-width: clamp(var(–min-viewport-width), var(–current-viewport-width), var(–max-viewport-width);<br />
/*<br />
Use the clamped viewport width in our calculation<br />
*/<br />
var(–ideal-font-size) * var(–clamped-viewport-width) / var(–ideal-viewport-width)<br />
);<br />
}<br />
} </p>
<p>Let’s make a helper for the unit conversions </p>
<p>Our code is quite verbose. Let’s write a simple SCSS function that converts our values from pixels to relative units. That way, we can import and reuse anywhere this anywhere without so much duplication: </p>
<p>/*<br />
Declare a SCSS function that takes a value to be scaled and<br />
ideal viewport width:<br />
*/<br />
@function scaleValue(<br />
$value,<br />
$idealViewportWidth: 1600px,<br />
$min: 350px,<br />
$max: 3840px<br />
) {<br />
@return calc(<br />
#{$value} * (clamp(#{$min}, 100vw, #{$max}) / #{$idealViewportWidth})<br />
);<br />
} </p>
<p>/*<br />
We can then apply it on any numeric CSS value. </p>
<p> Please note we are passing not pixel based, but numeric values:<br />
*/<br />
.myElement {<br />
width: #{scaleValue(500)};<br />
height: #{scaleValue(500)};<br />
box-shadow: #{scaleValue(2)} #{scaleValue(2)} rgba(black, 0.5);<br />
font-size: #{scaleValue(24)};<br />
} </p>
<p>Porting this to Javascript </p>
<p>Sometimes CSS doesn’t cut it and we have to use JavaScript to size a component. Let’s say we are constructing an SVG dynamically and we need to size its width and height properties based on an ideal design width. Here is the JavaScript to make it happen: </p>
<p>/*<br />
Our helper method to scale a value based on the device width<br />
*/<br />
const scaleValue = (value, idealViewportWidth = 1600) = > {<br />
return value * (window.innerWidth / idealViewportWidth)<br />
} </p>
<p>/*<br />
Create a SVG element and set its width, height and viewbox properties<br />
*/<br />
const IDEAL_SVG_WIDTH = 512<br />
const IDEAL_SVG_HEIGHT = 512 </p>
<p>const svgEl = document.createElement(‘svg’)<br />
/* Scale the width and height */<br />
svgEl.setAttribute(‘width’, scaleValue(IDEAL_SVG_WIDTH))<br />
svgEl.setAttribute(‘height’, scaleValue(IDEAL_SVG_WIDTH)) </p>
<p>/*<br />
We don’t really need to scale the viewBox property because it will<br />
perfectly match the ratio of the scaled width and height<br />
*/<br />
svg.setAttribute(‘viewBox’, `0 0 ${IDEAL_SVG_WIDTH} ${IDEAL_SVG_HEIGHT}`) </p>
<p>The drawbacks of this technique </p>
<p>This solution is not perfect. For example, one major drawback is that the the UIs are no longer zoomable. No matter how much the user zooms, the designs will stay locked as if they are viewed at 100% zoom. </p>
<p>That said, we can easily use traditional media queries, where we set different ideal numeric values at different viewport widths: </p>
<p>.myElement {<br />
width: #{scaleValue(500)};<br />
height: #{scaleValue(500)};<br />
box-shadow: #{scaleValue(2)} #{scaleValue(2)} rgba(black, 0.5);<br />
font-size: #{scaleValue(24)};<br />
@media (min-width: 64em) {<br />
width: #{scaleValue(800)};<br />
font-size: #{scaleValue(42)};<br />
}<br />
} </p>
<p>Now we can benefit from both media queries and our pixel-perfect linear scaling. </p>
<p>Wrapping up </p>
<p>All of this is an alternative way to implement fluid UIs. We treat the pixel-perfect values as pure numeric values, and multiply them by the difference between the current viewport width and the “ideal” viewport width from the designs. </p>
<p>I have used this technique extensively in my own work and hope that you will find some use of it too. </p>
<p>The post How to Get a Pixel-Perfect, Linearly Scaled UI appeared first on CSS-Tricks. You can support CSS-Tricks by being an MVP Supporter.</p>