0

I have a container with a fixed with. In this container there will be some text with a variable length. What I am trying to do is do automatically adjust the font-size of the text such that the it will fit into the container.

What is the best way to do that?

I have already tried to set the font-size with vm but this only resizes the text, when the container gets smaller and not when the text gets longer.

More precise my html and css look as follows and the text in label should resize if it is longer, to fit inot the label.

.input-wrapper {
  display: flex;
  flex-direction: row;
  width: 70%;
}

label {
  color: white;
  display: flex;
  flex-wrap: wrap;
  width: max-content;
  background-color: var(--violet);
  min-width: 30%;
  justify-content: center;
  align-items: center;
  word-wrap: break-word;
}

input {
  display: flex;
  border: 1px solid var(--violet);
  min-width: 70%;
}
<form onSubmit={this.handleSubmit}>
  <div className="input-wrapper">
    <label id="fixed">Gas cost</label>
    <input type="text"/>
  </div>
</form>
  • Have you seen [dynamically changing the size of font size based on text length using css and html](https://stackoverflow.com/q/18229230/1115360)? – Andrew Morton Nov 24 '21 at 10:42

1 Answers1

0

I think there is no CSS only solution to that. The unit vw / vh are related to the viewport and not to the parent container. So when your browser window gets bigger you could scale with that units your font-size.

What you would need is some JavaScript which scales the font-size based on the elements textContent length. Lets assume your base font size is 16px and you expect a label to have commonly a length between 1 and 80 characters. We would take the label content length and get a percentage in relation to the expected maximum 80 characters, limiting it to 100%. These percentage we will negate and use as our scaling factor. Then we will apply the scaling factor to get the scaled font size but again limit it to the minimum font size.

<label id="fixed">Some long content</label>
<script>
  function downscale(length, expectedMaxLength, baseFontSize, minFontSize) {
    const scalingFactor = 1 - Math.min(1 / expectedMaxLength * length, 1);
    return Math.ceil(Math.max(scalingFactor * (baseFontSize - minFontSize) + minFontSize, minFontSize));
  }

  const label = document.getElementById('fixed');
  const resizedFontSize = downscale(
    label.textContent.length,
    parseInt(window.getComputedStyle(label).fontSize, 10),
    8
  );
  label.style.fontSize = `${resizedFontSize}px`;
</script>
fragsalat
  • 500
  • 4
  • 14