Skip to content

Instantly share code, notes, and snippets.

@dwaynemac
Created May 9, 2023 20:49
Show Gist options
  • Save dwaynemac/07e0fad95822aa5b90df27452ed86551 to your computer and use it in GitHub Desktop.
Save dwaynemac/07e0fad95822aa5b90df27452ed86551 to your computer and use it in GitHub Desktop.
adjust font-size to fit container
import { Controller } from "@hotwired/stimulus"
// Ajusta el tamaño el font-size para que el texto entre en el elemento
// Ejemplo:
// <input type="text" data-controller="text-fit" "data-fit-text-default-size-value="5" data-fit-text-unit-value="rem" data-fit-text-step-value="0.1">
// data-controller="fit-text"
// data-fit-text-default-size-value="20" (required)
// data-fit-text-unit-value="px" (required)
// data-fit-text-step-value="1" (required)
export default class extends Controller {
static values = {
defaultSize: Number,
unit: String,
step: Number
}
connect() {
this.resize()
}
resize() {
// Retrieve the dimensions of the element.
const el = this.element
const elWidth = el.offsetWidth
const elHeight = el.offsetHeight
// Set the initial font size to a default value.
let fontSize = this.defaultSizeValue
// Use a loop to decrease the font size by 1 pixel at a time until the text fits within the element.
while (fontSize > 1) {
el.style.fontSize = `${fontSize}${this.unitValue}`
if (el.scrollWidth <= elWidth && el.scrollHeight <= elHeight) {
break
}
fontSize -= this.stepValue
}
// Set the font size to the last value that fit.
el.style.fontSize = `${fontSize}${this.unitValue}`
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment