Fitty

Makes text fit perfectly

README

Fitty, Snugly text resizing


Scales up (or down) text so it fits perfectly to its parent container.

Ideal for flexible and responsive websites.

License: MIT npm version
npm


[](https://www.buymeacoffee.com/rikschennink/)



Features


-   No dependencies
-   Easy setup
-   Optimal performance by grouping DOM read and write operations
-   Works with WebFonts (see example below)
-   Min and max font sizes
-   Support for MultiLine
-   Auto update when viewport changes
-   Monitors element subtree and updates accordingly

Installation


Install from npm:

  1. ```
  2. npm install fitty --save
  3. ```

Or download dist/fitty.min.js and include the script on your page like shown below.

Usage


Run fitty like shown below and pass an element reference or a querySelector. For best performance include the script just before the closing `` element.

  1. ``` html
  2. <div id="my-element">Hello World</div>
  3. <script src="fitty.min.js"></script>
  4. <script>
  5.     fitty('#my-element');
  6. </script>
  7. ```

The following options are available to pass to the fitty method.

OptionDefaultDescription
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
`minSize``16`The
`maxSize``512`The
`multiLine``true`Wrap
`observeMutations``MutationObserverInit`Rescale

Default MutationObserverInit configuration:

  1. ``` js
  2. {
  3.   subtree: true,
  4.   childList: true,
  5.   characterData: true
  6. }
  7. ```

You can pass custom arguments like this:

  1. ``` js
  2. fitty('#my-element', {
  3.     minSize: 12,
  4.     maxSize: 300,
  5. });
  6. ```

The fitty function returns a single or multiple Fitty instances depending on how it's called. If you pass a query selector it will return an array of Fitty instances, if you pass a single element reference you'll receive back a single Fitty instance.

MethodDescription
-------------------------------------------------------------------------------------------------
`fit()`Force
`freeze()`No
`unfreeze()`Resume
`unsubscribe()`Remove

PropertiesDescription
------------------------------------------
`element`Reference

  1. ``` js
  2. var fitties = fitty('.fit');

  3. // get element reference of first fitty
  4. var myFittyElement = fitties[0].element;

  5. // force refit
  6. fitties[0].fit();

  7. // stop updating this fitty and restore to original state
  8. fitties[0].unsubscribe();
  9. ```

Fitty dispatches an event named "fit" when a fitty is fitted.

EventDescription
----------------------------------------------------------------------
`"fit"`Fired

The detail property of the event contains an object which exposes the font size oldValue the newValue and the scaleFactor.

  1. ``` js
  2. myFittyElement.addEventListener('fit', function (e) {
  3.     // log the detail property to the console
  4.     console.log(e.detail);
  5. });
  6. ```

The fitty function itself also exposes some static options and methods:

OptionDefaultDescription
------------------------------------------------------------------------------------------------------------------------------------------
`fitty.observeWindow``true`Listen
`fitty.observeWindowDelay``100`Redraw

MethodDescription
-------------------------------------------------------------------------------------------------------------------------
`fitty.fitAll()`Refits

Performance


For optimal performance add a CSS selector to your stylesheet that sets the elements that will be resized to have white-space:nowrap and display:inline-block. If not, Fitty will detect this and will have to restyle the elements automatically, resulting in a slight performance penalty.

Suppose all elements that you apply fitty to are assigned the fit class name, add the following CSS selector to your stylesheet:

  1. ```css
  2. .fit {
  3.     display: inline-block;
  4.     white-space: nowrap;
  5. }
  6. ```

Should you only want to do this when JavaScript is available, add the following to the `` of your web page.

  1. ``` html
  2. <script>
  3.     document.documentElement.classList.add('js');
  4. </script>
  5. ```

And change the CSS selector to:

  1. ```css
  2. .js .fit {
  3.     display: inline-block;
  4.     white-space: nowrap;
  5. }
  6. ```

Do Not Upscale Text


Fitty calculates the difference in width between the text container and its parent container. If you use CSS to set the width of the text container to be equal to the parent container it won't scale the text.

This could be achieved by forcing the text container to be a block level element with display: block !important or setting its width to 100% with width: 100%.

Custom Fonts


Fitty does not concern itself with custom fonts. But it will be important to redraw Fitty text after a custom font has loaded (as previous measurements are probably incorrect at that point).

If you need to use fitty on browsers that don't have CSS Font Loading support (Edge and Internet Explorer) you can use the fantastic FontFaceObserver by Bram Stein to detect when your custom fonts have loaded.

See an example custom font implementation below. This assumes fitty has already been called on all elements with class name fit.

  1. ``` html
  2. <style>
  3.     /* Only set the custom font if it's loaded and ready */
  4.     .fonts-loaded .fit {
  5.         font-family: 'Oswald', serif;
  6.     }
  7. </style>
  8. <script>
  9.     (function () {
  10.         // no promise support (<=IE11)
  11.         if (!('Promise' in window)) {
  12.             return;
  13.         }
  14.         // called when all fonts loaded
  15.         function redrawFitty() {
  16.             document.documentElement.classList.add('fonts-loaded');
  17.             fitty.fitAll();
  18.         }
  19.         // CSS Font Loading API
  20.         function native() {
  21.             // load our custom Oswald font
  22.             var fontOswald = new FontFace('Oswald', 'url(assets/oswald.woff2)', {
  23.                 style: 'normal',
  24.                 weight: '400',
  25.             });
  26.             document.fonts.add(fontOswald);
  27.             fontOswald.load();
  28.             // if all fonts loaded redraw fitty
  29.             document.fonts.ready.then(redrawFitty);
  30.         }
  31.         // FontFaceObserver
  32.         function fallback() {
  33.             var style = document.createElement('style');
  34.             style.textContent =
  35.                 '@font-face { font-family: Oswald; src: url(assets/oswald.woff2) format("woff2");}';
  36.             document.head.appendChild(style);
  37.             var s = document.createElement('script');
  38.             s.src =
  39.                 'https://cdnjs.cloudflare.com/ajax/libs/fontfaceobserver/2.0.13/fontfaceobserver.standalone.js';
  40.             s.onload = function () {
  41.                 new FontFaceObserver('Oswald').load().then(redrawFitty);
  42.             };
  43.             document.body.appendChild(s);
  44.         }
  45.         // Does the current browser support the CSS Font Loading API?
  46.         if ('fonts' in document) {
  47.             native();
  48.         } else {
  49.             fallback();
  50.         }
  51.     })();
  52. </script>
  53. ```

Notes


-   Will not work if the fitty element is not part of the DOM.

-   If the parent element of the fitty element has horizontal padding the width calculation will be incorrect. You can fix this by wrapping the fitty element in another element.

  1. ``` html
  2. <div style="padding-left:100px">
  3.     <h1 class="fit">I'm a wonderful heading</h1>
  4. </div>
  5. ```

  1. ``` html
  2. <div style="padding-left:100px">
  3.     <div><h1 class="fit">I'm a wonderful heading</h1></div>
  4. </div>
  5. ```

Tested


-   Modern browsers
-   IE 10+

Note that IE will require CustomEvent polyfill:
https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent/CustomEvent#Polyfill

IE10 will require a polyfill for Object.assign:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign

Versioning


Versioning follows Semver.

License


MIT