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.
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.
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.
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.
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.
Scaling our UI
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.
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:
.cardWidget { .cardHeading { font-size: 16px; } }
Nothin’ fancy. Nothing we have not seen before. Being a pixel value, this will not scale.
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.
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:
/* 1600px is the ideal viewport width that the UI designers who created the dashboard used when designing their Figma artboards Please not we are not using pixel units here, treating it purely as a numeric value. */ --ideal-viewport-width: 1600; /* The actual width of the user device */ --current-viewport-width: 100vw; .cardWidget { .cardHeading { /* 16px is the ideal font size that the UI designers want for 1600px viewport width. Please note that we are not using pixel units here, treating it purely as a numeric value. */ --ideal-font-size: 16; /* Calculate the actual font size: We take our idealFontSize and multiply it by the difference between the current viewport width and the ideal viewport width. */ font-size: calc( var(--ideal-font-size) * (var(--current-viewport-width) / var(--ideal-viewport-width) ); } }
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:
--current-device-width: 100vw; // represents 1600px or full width of the screen --ideal-viewport-width: 1600; // notice that the ideal and current width match --ideal-font-size: 16; // this evaluates to: font-size: calc(16 * 1600px / 1600); // same as: font-size: calc(16 * 1px); // final result: font-size: 16px;
So, since our viewport width matches perfectly, our font-size ends being exactly 16px at the ideal viewport width of 1600px.
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:
font-size: calc(16 * 1366px / 1600); // same as: font-size: calc(16 * 0.85375px); // final result: font-size: 13.66px;
Or let’s say we are viewing this on a full high-definition display at 1920px wide:
font-size: calc(16 * 1920px / 1600); // same as: font-size: calc(16 * 1.2px); // final result: font-size: 19.2px;
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.
Here is a small demo I built to illustrate the technique:
Here’s a video for convienence:
Clamping the min and max viewport width
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:
--ideal-viewport-width: 1600; --current-viewport-width: 100vw; /* Set our minimum and maximum allowed layout widths: */ --min-viewport-width: 350px; --max-viewport-width: 3840px; .cardWidget { .cardHeading { --ideal-font-size: 16; font-size: calc( /* The clamp() function takes three comma separated expressions as its parameter, in the order of minimum value, preferred value and maximum value: */ --clamped-viewport-width: clamp(var(--min-viewport-width), var(--current-viewport-width), var(--max-viewport-width); /* Use the clamped viewport width in our calculation */ var(--ideal-font-size) * var(--clamped-viewport-width) / var(--ideal-viewport-width) ); } }
Let’s make a helper for the unit conversions
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:
/* Declare a SCSS function that takes a value to be scaled and ideal viewport width: */ @function scaleValue( $value, $idealViewportWidth: 1600px, $min: 350px, $max: 3840px ) { @return calc( #{$value} * (clamp(#{$min}, 100vw, #{$max}) / #{$idealViewportWidth}) ); } /* We can then apply it on any numeric CSS value. Please note we are passing not pixel based, but numeric values: */ .myElement { width: #{scaleValue(500)}; height: #{scaleValue(500)}; box-shadow: #{scaleValue(2)} #{scaleValue(2)} rgba(black, 0.5); font-size: #{scaleValue(24)}; }
Porting this to Javascript
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:
/* Our helper method to scale a value based on the device width */ const scaleValue = (value, idealViewportWidth = 1600) => { return value * (window.innerWidth / idealViewportWidth) } /* Create a SVG element and set its width, height and viewbox properties */ const IDEAL_SVG_WIDTH = 512 const IDEAL_SVG_HEIGHT = 512 const svgEl = document.createElement('svg') /* Scale the width and height */ svgEl.setAttribute('width', scaleValue(IDEAL_SVG_WIDTH)) svgEl.setAttribute('height', scaleValue(IDEAL_SVG_WIDTH)) /* We don't really need to scale the viewBox property because it will perfectly match the ratio of the scaled width and height */ svg.setAttribute('viewBox', `0 0 ${IDEAL_SVG_WIDTH} ${IDEAL_SVG_HEIGHT}`)
The drawbacks of this technique
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.
That said, we can easily use traditional media queries, where we set different ideal numeric values at different viewport widths:
.myElement { width: #{scaleValue(500)}; height: #{scaleValue(500)}; box-shadow: #{scaleValue(2)} #{scaleValue(2)} rgba(black, 0.5); font-size: #{scaleValue(24)}; @media (min-width: 64em) { width: #{scaleValue(800)}; font-size: #{scaleValue(42)}; } }
Now we can benefit from both media queries and our pixel-perfect linear scaling.
Wrapping up
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.
I have used this technique extensively in my own work and hope that you will find some use of it too.
以上がピクセルに完全なスケーリングされたUIを取得する方法の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

書くことができる「未来的な」JavaScriptがあります。 「ステージ0」とは、まだ提案であるJavaScript言語のアイデアを指します。それでも、誰かが向きを変えるかもしれません

2部構成のシリーズのこの2番目の記事では、Temani Afifは、Border-Imageプロパティを使用するのではなく、実験的なスクロール駆動型アニメーションを使用して、最初の記事からSTARレーティングコンポーネントを作成するための代替アプローチを示しています。

フォントはベクトルです。より多くのポイントを持つベクトルアートは、より少ないポイントのベクトルアートよりも大きなファイルになります。カスタムフォントがダウンロードされます。したがって、フォントが少ない

シンプルさは、Webデザインと開発における面白い形容詞です。私は確かに、これまでに行われたほぼすべてのプロジェクトの引用された目標です。誰もキックオフに進みます

非常に多くのWebプロジェクトは、NPMを使用して、フロントエンドとバックの両方で依存関係を引き込みます。 npmインストールと離れて、何千ものファイルを引き出します

ボーダーイメージを定期的に使用しています。しかし、それは最も多く使用されていないCSSツールの1つであり、私の人生では、その理由を理解することはできません。構文が厄介で直感的ではないため、人々が境界イメージを避けている可能性はありますか?おそらくそうです

開発は複雑です。私たちの仕事は、仕事を終わらせることと、安全で長続きする方法でその仕事をすることとの継続的な戦いです。


ホットAIツール

Undresser.AI Undress
リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover
写真から衣服を削除するオンライン AI ツール。

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

Video Face Swap
完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

人気の記事

ホットツール

MantisBT
Mantis は、製品の欠陥追跡を支援するために設計された、導入が簡単な Web ベースの欠陥追跡ツールです。 PHP、MySQL、Web サーバーが必要です。デモおよびホスティング サービスをチェックしてください。

mPDF
mPDF は、UTF-8 でエンコードされた HTML から PDF ファイルを生成できる PHP ライブラリです。オリジナルの作者である Ian Back は、Web サイトから「オンザフライ」で PDF ファイルを出力し、さまざまな言語を処理するために mPDF を作成しました。 HTML2FPDF などのオリジナルのスクリプトよりも遅く、Unicode フォントを使用すると生成されるファイルが大きくなりますが、CSS スタイルなどをサポートし、多くの機能強化が施されています。 RTL (アラビア語とヘブライ語) や CJK (中国語、日本語、韓国語) を含むほぼすべての言語をサポートします。ネストされたブロックレベル要素 (P、DIV など) をサポートします。

ドリームウィーバー CS6
ビジュアル Web 開発ツール

DVWA
Damn Vulnerable Web App (DVWA) は、非常に脆弱な PHP/MySQL Web アプリケーションです。その主な目的は、セキュリティ専門家が法的環境でスキルとツールをテストするのに役立ち、Web 開発者が Web アプリケーションを保護するプロセスをより深く理解できるようにし、教師/生徒が教室環境で Web アプリケーションを教え/学習できるようにすることです。安全。 DVWA の目標は、シンプルでわかりやすいインターフェイスを通じて、さまざまな難易度で最も一般的な Web 脆弱性のいくつかを実践することです。このソフトウェアは、

ZendStudio 13.5.1 Mac
強力な PHP 統合開発環境
