Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

142
Vistas
Set font-size automatically according to the element height

I have a text input and preview text div. I want the preview text font size to adjust automatically according to the given height. Please keep in mind, it will only see height to adjust its font size, width will be auto.
I have google and researched a lot, I have also tried them but these questions/answers are different than mine.
When i set the div height to 50px, it should automatically adjust the font size according to that height, height matters, height should not go bigger than the given one & when text goes to next line, then it should decrement the font size to fit the text to the height.
Here is the code:

const input = document.querySelector('input')
input.addEventListener('input', (e) => {
    const self = e.currentTarget
    const size = parseInt(self.value)
    const textElem = document.querySelector('.previewText')
    textElem.style.height = `${size}px`

    adjustText(size, textElem)
})

const adjustText = (size, textElem) => {
    const childElem = textElem.firstChild.nextElementSibling
    let fontSize = textElem.style.fontSize
    fontSize = fontSize.replace('px', '')
    for (let i = 0; i < size; i++) {
        if (textElem.offsetHeight > childElem.offsetHeight) {
            console.log('greater tha')
            textElem.style.fontSize = `${i}px`
        }
        if (textElem.offsetHeight < childElem.offsetHeight) {
            console.log('less than')
            textElem.style.fontSize = `${fontSize - 1}px`
        }
    }
}
<input type="number">
<div class="previewText">
    <div>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod.</div>
</div>

It's working almost right, but it's not working perfectly. Can someone please help me? I am stuck...

about 4 years ago · Santiago Gelvez
1 Respuestas
Responde la pregunta

0

Not sure I got your code right but I guess the condition in your for loop doesn't work.

You need to decrease font-size as long as the text height is larger than it's parent div like so:

    for(let i; textHeight>previewTextHeight; i++ ){}

Example snippet

(You can edit the text to check the font-size adjustment)

const fontSize = document.querySelector('#fontSize');
const previewText = document.querySelector('.previewText');
const textInner = document.querySelector('.textInner');
const currentFontSize = document.querySelector('.currentFontSize');

const adjustText = function() {
  let size = fontSize.value;
  previewText.style.fontSize = `${size*1}px`;
  previewText.style.height = `${size}px`;
  let previewTextHeight = previewText.clientHeight;
  let textHeight = Math.ceil(textInner.clientHeight);

  for (let i; textHeight > previewTextHeight; i++) {
    size -= 1;
    previewText.style.fontSize = `${size*1}px`;
    textHeight = Math.ceil(textInner.clientHeight);
  }
  currentFontSize.textContent = `fontSize: ${size} height: ${previewTextHeight}`;
}

//
adjustText();

fontSize.addEventListener('change', (e) => {
  adjustText()
})


textInner.addEventListener("input", (e) => {
  adjustText()
});
.previewText {
  outline: 1px solid #ccc;
  line-height: 1.2em;
  font-family: Arial;
}

.textInner:focus {
  outline: none
}
<p>Font-size</p>
<input id="fontSize" type="range" value="200" step="10" min="10" max="200">
<p>Editable text</p>
<div class="previewText">
  <div class="textInner" contentEditable>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod.</div>
</div>
<p class="currentFontSize"></p>

about 4 years ago · Santiago Gelvez Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda