Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

✨ Makes text fit perfectly

License

NotificationsYou must be signed in to change notification settings

rikschennink/fitty

Repository files navigation

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

Ideal for flexible and responsive websites.

Visit PQINA.nl for other useful Web Components

License: MITnpm versionnpm


Buy me a Coffee /Dev updates on Twitter


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:

npm install fitty --save

Or downloaddist/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</body> element.

<divid="my-element">Hello World</div><scriptsrc="fitty.min.js"></script><script>fitty('#my-element');</script>

The following options are available to pass to thefitty method.

OptionDefaultDescription
minSize16The minimum font size in pixels
maxSize512The maximum font size in pixels
multiLinetrueWrap lines when using minimum font size.
observeMutationsMutationObserverInitRescale when element contents is altered. Is set to false whenMutationObserver is not supported. Pass a custom MutationObserverInit config to optimize monitoring based on your project. By default contains the MutationObserverInit configuration below orfalse based on browser support.

Default MutationObserverInit configuration:

{subtree:true,childList:true,characterData:true}

You can pass custom arguments like this:

fitty('#my-element',{minSize:12,maxSize:300,});

Thefitty 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(options)Force a redraw of the current fitty element
freeze()No longer update this fitty on changes
unfreeze()Resume updates to this fitty
unsubscribe()Remove the fitty element from the redraw loop and restore it to its original state
PropertiesDescription
elementReference to the related element
varfitties=fitty('.fit');// get element reference of first fittyvarmyFittyElement=fitties[0].element;// force refitfitties[0].fit();// force synchronous refitfitties[0].fit({sync:true});// stop updating this fitty and restore to original statefitties[0].unsubscribe();

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

EventDescription
"fit"Fired when the element has been fitted to the parent container.

Thedetail property of the event contains an object which exposes the font sizeoldValue thenewValue and thescaleFactor.

myFittyElement.addEventListener('fit',function(e){// log the detail property to the consoleconsole.log(e.detail);});

Thefitty function itself also exposes some static options and methods:

OptionDefaultDescription
fitty.observeWindowtrueListen to the "resize" and "orientationchange" event on the window object and update fitties accordingly.
fitty.observeWindowDelay100Redraw debounce delay in milliseconds for when above events are triggered.
MethodDescription
fitty.fitAll(options)Refits all fitty instances to match their parent containers. Essentially a request to redraw all fitties. Theoptions object is passed to fitty instancefit() method.

Performance

For optimal performance add a CSS selector to your stylesheet that sets the elements that will be resized to havewhite-space:nowrap anddisplay: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 thefit class name, add the following CSS selector to your stylesheet:

.fit {display: inline-block;white-space: nowrap;}

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

<script>document.documentElement.classList.add('js');</script>

And change the CSS selector to:

.js .fit {display: inline-block;white-space: nowrap;}

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 withdisplay: block !important or setting its width to 100% withwidth: 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 haveCSS Font Loading support (Edge and Internet Explorer) you can use the fantasticFontFaceObserver 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 namefit.

<style>/* Only set the custom font if it's loaded and ready */    .fonts-loaded .fit {font-family:'Oswald', serif;    }</style><script>(function(){// no promise support (<=IE11)if(!('Promise'inwindow)){return;}// called when all fonts loadedfunctionredrawFitty(){document.documentElement.classList.add('fonts-loaded');fitty.fitAll();}// CSS Font Loading APIfunctionnative(){// load our custom Oswald fontvarfontOswald=newFontFace('Oswald','url(assets/oswald.woff2)',{style:'normal',weight:'400',});document.fonts.add(fontOswald);fontOswald.load();// if all fonts loaded redraw fittydocument.fonts.ready.then(redrawFitty);}// FontFaceObserverfunctionfallback(){varstyle=document.createElement('style');style.textContent='@font-face { font-family: Oswald; src: url(assets/oswald.woff2) format("woff2");}';document.head.appendChild(style);vars=document.createElement('script');s.src='https://cdnjs.cloudflare.com/ajax/libs/fontfaceobserver/2.0.13/fontfaceobserver.standalone.js';s.onload=function(){newFontFaceObserver('Oswald').load().then(redrawFitty);};document.body.appendChild(s);}// Does the current browser support the CSS Font Loading API?if('fonts'indocument){native();}else{fallback();}})();</script>

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.

<!-- Problems --><divstyle="padding-left:100px"><h1class="fit">I'm a wonderful heading</h1></div>
<!-- No more problems --><divstyle="padding-left:100px"><div><h1class="fit">I'm a wonderful heading</h1></div></div>

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 forObject.assign:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign

Versioning

Versioning followsSemver.

License

MIT

Sponsor this project

    Packages

    No packages published

    Contributors13


    [8]ページ先頭

    ©2009-2026 Movatter.jp