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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

예, YoushouldLearnbothflexBoxAndgrid.1) FlexBoxisIdealforone-Dimensional, FlexiblelayoutSlikenavigationMenus.2) GridexCelsIntwo-Dimensional, ComplexDesignsSuchasmagazinElayouts.3) 결합 된 BothenSlayoutFlexibility 및 HeartingFortructur

자신의 코드를 리팩터링하는 것은 어떤 모습입니까? John Rhea는 자신이 쓴 오래된 CSS 애니메이션을 선택하고 최적화하는 사고 과정을 살펴 봅니다.

cssanimationsarenherinly에 hardbutreepracticenderstandingofcsspropertiesandtimingflestions.1) startsimpleants withsimpleatslikeScalingabuttononHoverusingKeyframes.2) useAsingfuctionslikecubic-bezierfornateffects, 그러한 분위기, 3)

@keyframesispopularduetoitstativerstatility 및 powerincreatingsmoothcssanimations.keytricksinclude : 1) states 사이에 moothtransitionsbettites, 2) 애니메이션 multiplepropertiessimultory, 3) vendorPixesforBrowsercompatibility, 4) 빗질을 사용하여

csScounterSearedTomanageAutomaticNumberingInberingInwebDesigns.1) 1) theCanbeusedfortablestoffContents, ListItems 및 CustomNumbering.2) AdvancedUsesInSinestedNumberingsystems.3) CreativeUseNvolvecust를 CreativeSinvolecust.4) CreativeSinvolvecust

특히 모바일 장치에 스크롤 그림자를 사용하는 것은 Chris가 이전에 다룬 미묘한 UX입니다. Geoff는 애니메이션 타임 라인 속성을 사용하는 새로운 접근 방식을 다루었습니다. 또 다른 방법이 있습니다.

빠른 새로 고침을 통해 실행합시다. 이미지 맵은 html 3.2로 돌아가는데, 먼저 서버 측 맵과 클라이언트 측지 맵은 맵 및 영역 요소를 사용하여 이미지를 통해 클릭 가능한 영역을 정의했습니다.

Devs State Survey는 이제 참여에 개방되어 있으며, 이전 설문 조사와 달리 코드, 직장, 건강, 취미 등을 제외한 모든 것을 포함합니다.


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

DVWA
DVWA(Damn Vulnerable Web App)는 매우 취약한 PHP/MySQL 웹 애플리케이션입니다. 주요 목표는 보안 전문가가 법적 환경에서 자신의 기술과 도구를 테스트하고, 웹 개발자가 웹 응용 프로그램 보안 프로세스를 더 잘 이해할 수 있도록 돕고, 교사/학생이 교실 환경 웹 응용 프로그램에서 가르치고 배울 수 있도록 돕는 것입니다. 보안. DVWA의 목표는 다양한 난이도의 간단하고 간단한 인터페이스를 통해 가장 일반적인 웹 취약점 중 일부를 연습하는 것입니다. 이 소프트웨어는

VSCode Windows 64비트 다운로드
Microsoft에서 출시한 강력한 무료 IDE 편집기

Eclipse용 SAP NetWeaver 서버 어댑터
Eclipse를 SAP NetWeaver 애플리케이션 서버와 통합합니다.

PhpStorm 맥 버전
최신(2018.2.1) 전문 PHP 통합 개발 도구