Home > Software design >  How to auto resize font size to smaller when text is longer in a parent container?
How to auto resize font size to smaller when text is longer in a parent container?

Time:08-18

Im trying to make a text later will be JavaScript input into preview in a container(like name). So short name will be no problem since can be fit in the container, but the long name will trouble out of the container. Also I want the container to be fix width & height , only the text will be resize into smaller font

example for long text:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Test</title>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-KyZXEAg3QhqLMpG8r 8fhAXLRk2vvoC2f3B09zVXn8CA5QIVfZOJ3BCsw2P0p/We" crossorigin="anonymous">

</head>
<body>
    <div  
    style=" margin-top: 20px;
            width: 200px;
            height: 50px;
            border: 1px solid red;
            text-align: center;">
        <p>lorem ipsum dolor sit amet, consectetur adipisicing elit. Lorem ipsum dolor sit</p>
    </div>
</body>
</html>

example for short text:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Test</title>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-KyZXEAg3QhqLMpG8r 8fhAXLRk2vvoC2f3B09zVXn8CA5QIVfZOJ3BCsw2P0p/We" crossorigin="anonymous">

</head>
<body>
    <div  
    style=" margin-top: 20px;
            width: 200px;
            height: 50px;
            border: 1px solid red;
            text-align: center;">
        <p>lorem ipsum </p>
    </div>
</body>

CodePudding user response:

You can add javascript below the body that will count how many characters have

and change the font to fit the container:

add class to

<p class='text'>lorem ipsum dolor sit amet, consectetur adipisicing elit. Lorem ipsum dolor sit</p>

const text = document.querySelector('.text');

if (text.textContent.length > 60){
    text.style.fontSize = '12px'
}

CodePudding user response:

I did something similar to this recently, although my approach was to just cap the input at the width of the input (as the user is typing). Reducing the text size will only work to a certain extent, as the text size will get unreadable very quickly. You'd probably want to look at either setting a hard limit, or allowing it to wrap instead.

Without sharing any of your JavaScript it's hard to know where to start with this, so I'll give you the line in question that worked for me, and you'll have add the eventListener or whatever condition you're planning on using to check the length.

To limit text to the width of the input:

let myInput = document.getElementById("Name"); // Assuming you've given your input an ID of "Name"
if (myInput.scrollWidth > myInput.clientWidth){
    myInput.innerText = myInput.innertext.substring(0, myInput.innerHTML.length-1);
}

To explicitly do what you're asking, you'd change the line in the if statement to this:

myInput.style.fontSize = parseInt(myInput.style.fontSize) -1   "px";

Let me know if it doesn't work or you don't understand it and I'll have another look.

Edit: The reason for checking scrollWidth vs clientWidth is because if you're not using a monospaced font, a "w" is wider than an "i", so you can fit a lot more "i"s than you can "w"s

CodePudding user response:

As you asked : "I want the container to be fix width & height , only the text will be resize into smaller font"

I used JavaScript's in-built getComputedStyle function to get the height of both the parent( div ) and its child( p ). Then did some logic

if (parentHeight <= childHeight) {

   // reducing the fontsize of child
   // checking the condition again and decreasing the size until condition is false
}

Here is an working examples of 'How to Implement this in your Code':

For Long Text:

// Function to reduce the font size of the Container's child according to the Height
const fontResizer = () => {
  let container = document.querySelector(".container")
  let para = document.querySelector(".container .name")

  let containerHeight = window.getComputedStyle(container).height.replace("px", "")
  let paraHeight = window.getComputedStyle(para).height.replace("px", "")

  if (containerHeight <= paraHeight) {
    let paraSize = window.getComputedStyle(para).fontSize.replace("px", "")
    para.style.fontSize = `${paraSize-1}px`
    fontResizer()
  }

}

fontResizer()
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Test</title>
  <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-KyZXEAg3QhqLMpG8r 8fhAXLRk2vvoC2f3B09zVXn8CA5QIVfZOJ3BCsw2P0p/We" crossorigin="anonymous">

</head>

<body>
  <div  style=" margin-top: 20px;
            width: 200px;
            height: 50px;
            border: 1px solid red;
            text-align: center;">
    <p >lorem ipsum dolor sit amet, consectetur adipisicing elit. Lorem ipsum dolor sit</p>
  </div>
</body>

</html>

For Short Text:

// Function to reduce the font size of the Container's child according to the Height
const fontResizer = () => {
  let container = document.querySelector(".container")
  let para = document.querySelector(".container .name")

  let containerHeight = window.getComputedStyle(container).height.replace("px", "")
  let paraHeight = window.getComputedStyle(para).height.replace("px", "")

  if (containerHeight <= paraHeight) {
    let paraSize = window.getComputedStyle(para).fontSize.replace("px", "")
    para.style.fontSize = `${paraSize-1}px`
    fontResizer()
  }

}

fontResizer()
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Test</title>
  <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-KyZXEAg3QhqLMpG8r 8fhAXLRk2vvoC2f3B09zVXn8CA5QIVfZOJ3BCsw2P0p/We" crossorigin="anonymous">

</head>

<body>
  <div  style=" margin-top: 20px;
                width: 200px;
                height: 50px;
                border: 1px solid red;
                text-align: center;">
    <p >lorem ipsum </p>
  </div>
</body>

</html>

  • Related