recherche
Maisoninterface Webtutoriel CSSComment obtenir une interface utilisateur à l'échelle linéairement parfaite et à l'échelle linéaire

How to Get a Pixel-Perfect, Linearly Scaled UI

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.

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
@keyframes vs transitions CSS: quelle est la différence?@keyframes vs transitions CSS: quelle est la différence?May 14, 2025 am 12:01 AM

@KeyFramesAndcsstransitionsDiffeRinComplexity: @ KeyframesAllowsfordEtailedanimationSequences, tandis que les StransitionShandlesImpLestateChanges.USECSSTRANSITIONSFORHOVEFFECTSLILLOBUTTONCOLORCHANGES, et @ KeyframesFransintricateAralienslikeTatationSpinners.

Utilisation de pages CMS pour la gestion de contenu du site statiqueUtilisation de pages CMS pour la gestion de contenu du site statiqueMay 13, 2025 am 09:24 AM

Je sais, je sais: il y a une tonne d'options de système de gestion de contenu disponibles, et bien que je les teste plusieurs, aucun n'a vraiment été celui, y & # 039; savoir? Des modèles de tarification étranges, une personnalisation difficile, certains finissent même par devenir un tout

Le guide ultime pour lier les fichiers CSS dans HTMLLe guide ultime pour lier les fichiers CSS dans HTMLMay 13, 2025 am 12:02 AM

La liaison des fichiers CSS à HTML peut être réalisée en utilisant des éléments dans une partie de HTML. 1) Utilisez des balises pour relier les fichiers CSS locaux. 2) Plusieurs fichiers CSS peuvent être implémentés en ajoutant plusieurs balises. 3) Les fichiers CSS externes utilisent des liens URL absolus, tels que. 4) Assurez-vous que l'utilisation correcte des chemins de fichier et de l'ordre de chargement du fichier CSS et optimiser les performances peuvent utiliser le préprocesseur CSS pour fusionner les fichiers.

CSS Flexbox vs Grid: une revue complèteCSS Flexbox vs Grid: une revue complèteMay 12, 2025 am 12:01 AM

Le choix de Flexbox ou de la grille dépend des exigences de mise en page: 1) Flexbox convient aux dispositions unidimensionnelles, telles que la barre de navigation; 2) La grille convient aux dispositions bidimensionnelles, telles que les dispositions de magazines. Les deux peuvent être utilisés dans le projet pour améliorer l'effet de mise en page.

Comment inclure les fichiers CSS: méthodes et meilleures pratiquesComment inclure les fichiers CSS: méthodes et meilleures pratiquesMay 11, 2025 am 12:02 AM

La meilleure façon d'inclure des fichiers CSS est d'utiliser des balises pour introduire des fichiers CSS externes dans la pièce HTML. 1. Utilisez des balises pour introduire des fichiers CSS externes, tels que. 2. Pour les petits ajustements, le CSS en ligne peut être utilisé, mais doit être utilisé avec prudence. 3. Les grands projets peuvent utiliser des préprocesseurs CSS tels que SASS ou moins pour importer d'autres fichiers CSS via @Import. 4. Pour les performances, les fichiers CSS doivent être fusionnés et CDN doit être utilisé et compressé à l'aide d'outils tels que CSSNANO.

Flexbox vs Grid: Dois-je les apprendre tous les deux?Flexbox vs Grid: Dois-je les apprendre tous les deux?May 10, 2025 am 12:01 AM

Oui, vous émeuble-chouchoudion-dimensionnal, flexiblelayAndavigationMenus.2)

Mécanique orbitale (ou comment j'ai optimisé une animation de clés CSS)Mécanique orbitale (ou comment j'ai optimisé une animation de clés CSS)May 09, 2025 am 09:57 AM

À quoi cela ressemble-t-il de refactor votre propre code? John Rhea sépare une vieille animation CSS qu'il a écrite et traverse le processus de réflexion pour l'optimiser.

Animations CSS: est-il difficile de les créer?Animations CSS: est-il difficile de les créer?May 09, 2025 am 12:03 AM

CSSANIMATIONSARENOTINÉMENT HAUTS BUTREQUIREPRACTICIT ENCRIPTION DES PROFESSIONS DESPROPERTIES ET TROUVEMENT

See all articles

Outils d'IA chauds

Undresser.AI Undress

Undresser.AI Undress

Application basée sur l'IA pour créer des photos de nu réalistes

AI Clothes Remover

AI Clothes Remover

Outil d'IA en ligne pour supprimer les vêtements des photos.

Undress AI Tool

Undress AI Tool

Images de déshabillage gratuites

Clothoff.io

Clothoff.io

Dissolvant de vêtements AI

Video Face Swap

Video Face Swap

Échangez les visages dans n'importe quelle vidéo sans effort grâce à notre outil d'échange de visage AI entièrement gratuit !

Article chaud

<🎜>: Bubble Gum Simulator Infinity - Comment obtenir et utiliser les clés royales
4 Il y a quelques semainesBy尊渡假赌尊渡假赌尊渡假赌
Nordhold: Système de fusion, expliqué
4 Il y a quelques semainesBy尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers of the Witch Tree - Comment déverrouiller le grappin
3 Il y a quelques semainesBy尊渡假赌尊渡假赌尊渡假赌

Outils chauds

Envoyer Studio 13.0.1

Envoyer Studio 13.0.1

Puissant environnement de développement intégré PHP

VSCode Windows 64 bits Télécharger

VSCode Windows 64 bits Télécharger

Un éditeur IDE gratuit et puissant lancé par Microsoft

PhpStorm version Mac

PhpStorm version Mac

Le dernier (2018.2.1) outil de développement intégré PHP professionnel

Adaptateur de serveur SAP NetWeaver pour Eclipse

Adaptateur de serveur SAP NetWeaver pour Eclipse

Intégrez Eclipse au serveur d'applications SAP NetWeaver.

Navigateur d'examen sécurisé

Navigateur d'examen sécurisé

Safe Exam Browser est un environnement de navigation sécurisé permettant de passer des examens en ligne en toute sécurité. Ce logiciel transforme n'importe quel ordinateur en poste de travail sécurisé. Il contrôle l'accès à n'importe quel utilitaire et empêche les étudiants d'utiliser des ressources non autorisées.