1

I'm having trouble figuring out how to make text of a different size automatically scale to fit the size of a container. I originally thought I could do this use vw, vh units, but that seems not to work when the text is of a different length. I've also tried using FitText, but that doesn't seem to work either (I can post the code if needed).

I've made a very simple version below via jsfiddle. What kind of styling can I use to make the input text scale to fit 100% of the container, regardless of the length? Perhaps this requires a bit of JS to calculate the total line length and then create the font size from this? That seems like it would only work with fixed-width type.

Any thoughts? Thanks!

https://jsfiddle.net/mpecirno/euacdyfz/1/

JS

function change () {

    var myNewTitle = document.getElementById('myTextField').value;
    if( myNewTitle.length==0 ){
        alert('help me make this text fit to the container size!');
        return;
    }

    var title = document.getElementById('title');
    title.innerHTML = myNewTitle;

}

HTML

<div id="container">
    <h1 id="title">I am text with different lengths</h1>
</div>
<p></p>

<input type="text" id="myTextField"/>
<input type="submit" id="byBtn" value="Change" onclick="change()"/>

CSS

#container{
  width: 300px;
  height: 250px;
  outline: 1px solid #000;
}

h1 {
  font-family: 'Walsheim', arial black, sans-serif;
  font-size: calc(6vw);
  font-weight: bold;
  vertical-align: middle;
  color: var(--G1);
}
Brian
  • 1,873
  • 16
  • 25
Michael
  • 11
  • 1

0 Answers0