Make text fit container, prevent overflow and underflow.

Overview

AutoTextSize

Make text fit container, prevent overflow and underflow.

The font size of the text is adjusted so that it precisely fills its container. It uses computed width and height so it works for all types of fonts and automatically re-runs when the element resizes.

Live demo.

Single-line mode

The text fills the width of the container, without wrapping to more than one line.

Multi-line mode

The text fills both the width and the height of the container, allowing wrapping to multiple lines.

React component

The AutoTextSize component automatically re-runs when children changes and when the element resizes.

import { AutoTextSize } from 'auto-text-size'

export const Title = ({ text }) => {
  return (
    <div style={{ maxWidth: '60%', margin: '0 auto' }}>
      <AutoTextSize>{text}</AutoTextSize>
    </div>
  )
}

AutoTextSize props

Name Type Default Description
multiline boolean false Allow text to wrap to multiple lines.
minFontSizePx number 8 The minimum font size to be used.
maxFontSizePx number 160 The maximum font size to be used.
fontSizePrecisionPx number 0.1 The algorithm stops when reaching the precision.
as string | ReactComponent 'div' The underlying component that AutoTextSize will use.

Vanilla function

Zero dependencies.

import { autoTextSize } from 'auto-text-size'

// autoTextSize runs the returned function directly and
// re-runs it when the container element resize.
const updateTextSize = autoTextSize(options)

// All invocations are throttled for performance. Manually
// call this if the content changes and needs to re-adjust.
updateTextSize()

// Disconnect the resize observer when done.
updateTextSize.disconnect()

One-off:

import { updateTextSize } from 'auto-text-size'

updateTextSize(options)

autoTextSize options

Name Type Default Description
innerEl HTMLElement The inner element to be auto sized.
containerEl HTMLElement The container element defines the dimensions.
multiline boolean false Allow text to wrap to multiple lines.
minFontSizePx number 8 The minimum font size to be used.
maxFontSizePx number 160 The maximum font size to be used.
fontSizePrecisionPx number 0.1 The algorithm stops when reaching the precision.

Details

  • The single-line algorithm predicts how the browser will render text in a different font size and iterates until converging within fontSizePrecisionPx (usually 1-2 iterations).
  • The multi-line algorithm performs a binary search among the possible font sizes until converging within fontSizePrecisionPx (usually ~10 iterations). There is no reliable way of predicting how the browser will render text in a different font size when multi-line text wrap is at play.
  • Performance. Each iteration has a performance hit since it triggers a layout reflow. Multiple mesures are taken to minimize the performance impact. As few iterations as possible are executed, throttling is performed using requestAnimationFrame and ResizeObserver is used to recompute text size only when needed.
  • No overflow. After converging, the algorithm runs a second loop to ensure that no overflow occurs. Underflow is preferred since it doesn't look visually broken like overflow does. Some browsers (eg. Safari) are not good with sub-pixel font sizing, making it so that significant visual overflow can occur unless we adjust for it.
  • Font size is used rather than the scale() CSS function since it is simple and works very well. The the scale() function wouldn't support multi-line text wrap and it tends to make text blurry in some browsers.

Developing

When developing one typically wants to see the output in the example application without having to publish and reinstall. This is achieved by linking the local package into the example app.

Because of issues with yarn link, Yalc is used instead. A linking approach is preferred over yarn workspaces since we want to use the package as it would appear in the real world.

npm i yalc -g
yarn
yarn watch

# Other terminal
cd example
yarn
yalc link auto-text-size
yarn dev

Yalc and HMR

Using yalc link (or yalc add--link) makes it so that Next.js HMR detects updates instantly.

Publishing

# Update version number
yarn clean && yarn build
npm publish
You might also like...

A container-friendly alternative to os.cpus().length. Both cgroups v1 and cgroups v2 are supported.

node-cpu-count A container-friendly alternative to os.cpus().length. Both cgroups v1 and cgroups v2 are supported. Installation $ npm install node-cpu

Jan 17, 2022

Jugglr is a tool for managing test data and running tests with a dedicated database running in a Docker container.

Jugglr Jugglr is a tool for managing test data and running tests with a lightweight, dedicated database. Jugglr enables developers, testers, and CI/CD

Aug 20, 2022

A docker container with a wide variety of tools for debugging and setting up micro-services

Frame One Software Placeholder There are numerous times during the dev ops deployments, that a placeholder container is needed. In the past, Frame One

May 29, 2022

The invoker based on event model provides an elegant way to call your methods in another container via promisify functions

The invoker based on event model provides an elegant way to call your methods in another container via promisify functions. (like child-processes, iframe, web worker etc).

Dec 29, 2022

Container Image Signing & Verifying on Ethereum [Testnet]

Container Image Signing & Verifying on Ethereum [Testnet]

cosigneth An experimental decentralized application for storing and verifying container image signatures as an NFT on Ethereum cosigneth, is a decentr

Jul 4, 2022

Mailbox is the predictable states & transitions container for actors.

Mailbox is the predictable states & transitions container for actors.

Mailbox (turns XState Machine into a REAL Actor) Mailbox is an NPM module built on top of the XState machine, by adding a message queue to the XState

Aug 24, 2022

ContainerMenu is an API for BDSX that allows you to create fake interactive container menus !

ContainerMenu is an API for BDSX that allows you to create fake interactive container menus !

ContainerMenu - A BDSX API ContainerMenu is an API for BDSX that allows you to create fake interactive container menus ! Features Multiple containers

Oct 28, 2022

Pin any element within a container

jQuery.pin Ever wanted to pin something to the side of a text? Ever needed a subtle sticky element to quietly hang around as you scroll down? Jquery.P

Nov 30, 2022

Public repository of assets used during editions of AWS LATAM Container Roadshow event.

LATAM Containers Roadshow This is the official repository of assets related to LATAM Containers Roadshow, an all-day customer-facing event to highligh

Dec 6, 2022
Owner
Sana Labs
Personalized, collaborative learning
Sana Labs
This is a website for a simple to do list, where you can add and remove tasks, edit and reorder them as you see fit.

To-Do-List This is a website for a simple to do list, where you can do the following: Add the tasks you want to do. Remove any tasks you finished alre

Ammar Hamlaoui 7 Apr 6, 2022
Node.js package with a customized HTTP and HTTPS agents to prevent SSRF with hosts validations and custom DNS feature.

http-agent-dns This is a Node.js package with a customized HTTP and HTTPS agents to prevent SSRF with hosts validations with a possibility to use a cu

Bruno Germano 4 Jul 21, 2022
Convert your SVG file directly to Flutter paths and prevent all the messing with bezier curves.

svg-to-flutter-path-converter Convert your SVG file directly to Flutter paths and prevent all the messing with bezier curves. Flutter Clutter The tool

null 30 Jan 2, 2023
Veselin Petranchev 2 Oct 11, 2022
LunaSec - Open Source Security Software built by Security Engineers. Scan your dependencies for Log4Shell, or add Data Tokenization to prevent data leaks. Try our live Tokenizer demo: https://app.lunasec.dev

Our Software We're a team of Security Engineers on a mission to make awesome Open Source Application Security tooling. It all lives in this repo. Here

LunaSec 1.2k Jan 7, 2023
Statically prevent 404s in your Next.js applications using TypeScript

next-static-paths Statically prevent HTTP 404 Not Found in your Next.js applications using TypeScript and code generation. Features ?? A command-line

Gal Schlezinger 23 Jul 3, 2022
↕️ A little Alpine.js plugin to automatically resize a textarea to fit its content.

↕️ Alpine Autosize ↕️ A little Alpine.js plugin to automatically resize a textarea to fit its content. ?? Installation CDN Include the following <scri

Marc Reichel 42 Nov 5, 2022
An npm package with Tailwind CSS utility classes for creating responsive grid columns without media queries using auto fit.

Grid Auto Fit for Tailwind CSS A plugin that helps you create a responsive grid layout in Tailwind CSS without using media queries. It uses the auto-f

Thirus 80 Dec 28, 2022
Moject is a IoC container and an app factory built around the modules idea of Angular and NestJs.

Moject Moject is an IoC container and an app factory package built around the modules idea of Angular and NestJs. Usage npm install moject Use @Mo

Alexander 4 Dec 4, 2022
The app's backend is written in Python (Flask) and for search it uses Elasticsearch. I used this app as candidate application for learning out how to build, run and deploy a multi-container environment (docker-compose).

foodtrucks-app-docker-compose The app's backend is written in Python (Flask) and for search it uses Elasticsearch. I used this app as candidate applic

Selçuk Şan 3 Oct 24, 2022