Automatically adjust text size within div based on width dimensions

Dealing with a specific issue here. I have a div that has a fixed width and height (227px x 27px). Inside this div, there is content such as First and Last name, which can vary in length. Sometimes the name is short, leaving empty space in the div, but sometimes it's long and requires text resizing to fit within the div. Additionally, I want to set a maximum font size.

My HTML code appears as follows:

<div class="Basic-Text-Frame _idGenPageitem-6" id="fitin">
  <p class="Basic-Paragraph ParaOverride-1">
     <span class="CharOverride-2" ><?php echo $userdata->display_name;?></span>
  </p>
</div>

CSS styling:

div.Basic-Text-Frame {
 border-style:solid;
}
p.Basic-Paragraph {
  color:#000000;
  font-family:"Minion Pro", serif;
  font-size:12px;
  font-style:normal;
  font-variant:normal;
  font-weight:normal;
  line-height:1.2;
  margin-bottom:0;
  margin-left:0;
  margin-right:0;
  margin-top:0;
  orphans:1;
  page-break-after:auto;
  page-break-before:auto;
  text-align:left;
  text-decoration:none;
  text-indent:0;
  text-transform:none;
  widows:1;
}
div._idGenPageitem-6 {
  height:27px;
  left:0px;
  overflow:hidden;
  position:absolute;
  top:0px;
  width:227px;
  z-index:0;
}
p.ParaOverride-1 {
  text-align:center;
}
span.CharOverride-2 {
  color:#5b9b98;
  font-family:Garamond, serif;
  font-size:x-large;
  font-style:normal;
  font-variant:small-caps;
  font-weight:normal;
  text-transform:none;
  max-height: 29px;
}

I have experimented with various solutions like resizing font-size according to div size, using suggested answers from Stack Overflow, trying out plugins like flowType and FitText but couldn't achieve the desired result. Hence, I turned to ask this question.

The main issue is that longer text wraps into a new row instead of adjusting to fit within the given div box. When setting the span height to "absolute," it keeps changing back to "auto."

Attached is an image illustrating the problem at hand.

Any suggestions on resolving this dilemma?

Answer №1

Implement this function on page load to adjust the text size as needed. The key aspect in the css is white-space: nowrap which prevents the text from moving onto a new line.
Ensure that the test span "d" has the same font family, style and weight as the actual text.

function adjustTextSize()
{
    var maxWidth = 227, maxHeight = 27, maxSize = 20;
    var elements = document.getElementsByClassName("fitin");
    var dummySpan = document.createElement("span");
    dummySpan.style.fontSize = maxSize + "px";

    for (var j = 0; j < elements.length; j++)
    {
        dummySpan.innerHTML = elements[j].innerHTML;
        document.body.appendChild(dummySpan);
        var widthVal = dummySpan.offsetWidth;
        var heightVal = dummySpan.offsetHeight;
        document.body.removeChild(dummySpan);
        var scaleX = widthVal > maxWidth ? maxWidth / widthVal : 1;
        var scaleY = heightVal > maxHeight ? maxHeight / heightVal : 1;
        var newSize = Math.min(scaleX, scaleY) * maxSize;
        elements[j].style.fontSize = newSize + "px";
    }
}

adjustTextSize();
DIV
{
    width: 227px;
    height: 27px;
    overflow: hidden;
    margin-bottom: 9px;
    background-color: silver;
}

P
{
    margin: 0px;
    color: black;
    font-size: 20px;
    text-align: center;
    white-space: nowrap;
}
<DIV>
    <P>
         <SPAN CLASS="fitin">Short Guy</SPAN>
    </P>
</DIV>
<DIV>
    <P>
         <SPAN CLASS="fitin">Just A Random Regular Person</SPAN>
    </P>
</DIV>
<DIV>
    <P>
         <SPAN CLASS="fitin">A Really Very Extraordinarily Long And Tall Woman</SPAN>
    </P>
</DIV>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Setting up dynamic routing in AngularJS for links

I am facing some confusion regarding routing in AngularJS. Normally, we can configure routes in angular.config() when the angular module is loaded. At that time, we define static information such as routePath, templateUrl, and controller. However, I am u ...

Changing the background color of required inputs that are empty using jQuery

I need help customizing the background color of required input fields that are left empty when a user submits a form. Some of the fields are optional, but I want only the required ones to be highlighted in red. Specifically, the required fields have been ...

Redirecting asynchronously in Node.js with no use of AJAX

I've been struggling with this issue for days and have already sought help, but nothing seems to be working. Whenever I attempt to redirect from a POST request in node, the browser doesn't respond. Here's how my app is structured: ./ confi ...

The expiration time and date for Express Session are being inaccurately configured

I'm experiencing an issue with my express session configuration. I have set the maxAge to be 1 hour from the current time. app.use( session({ secret: 'ASecretValue', saveUninitialized: false, resave: false, cookie: { secure ...

Analyzing the current time against a user-inputted time using Javascript

Looking at this html and javascript code, the goal is to compare an input time with the current time. If the input time is less than 2 hours, "Less time" should be displayed in the label; if it's more than 2 hours, then "sufficient time" should appear ...

"Trouble arises when dealing with nested object arrays in Formik and handling changes in a child

I am struggling with passing a value to handleChange in formik validation. To address this issue, I created a component whose quantity is dynamically added based on the number of numChild. My goal is to allow users to click an icon and add any number of sk ...

Updating the parent's data by modifying data in the child component in VueJS

When I use multiple components together for reusability, the main component performs an AJAX call to retrieve data. This data is then passed down through different components in a chain of events. <input-clone endpoint="/api/website/{{ $website->id ...

C# MVC alert platform

Currently developing a C# MVC 4 app and aiming to integrate a notification system similar to Facebook's. I am considering implementing a table for each event to store notifications, then using AJAX calls every minute to fetch notifications for the cu ...

Traversing a deeply nested array of objects, comparing it with a separate array of objects

I am currently learning Javascript and facing a challenge involving looping through nested arrays of objects and filtering another array based on specific properties. Let's take a look at the structure of both arrays: const displayArr = { section ...

How can the <animate /> tag be triggered using only CSS and HTML?

Looking for a way to trigger the animation rules of the <animate /> tag using only HTML and CSS. Is there a new standard in HTML and CSS that allows something like input:checked ~ svg animate {enabled:true;} coming up in 2020? Or some other creative ...

Unable to set the cookie when using the fetch API

My node.js server is listening on port 3001. WITHIN THE REACT FILE On the login page component. fetch('http://localhost:3001/api/login',{ method:'POST', headers: { Accept: 'application/json', ...

What are some effective strategies for optimizing the organization of express middlewares?

Currently, I have successfully implemented the following code using node and express. The code is located in file app.js app.use(function (req, res, next) { fs.mkdir('uploads/', function (e) { if (!!e && e.code !== 'EEX ...

Effortlessly adjust item width in CSS Grid

I am currently utilizing CSS Grid to showcase various tags. If a tag happens to be quite large, with a width exceeding 150px, I would ideally like that specific item to expand across multiple columns as necessary. For instance, in the visual representation ...

import a function from jQuery that has been defined in an external JavaScript file

Whenever I attempt to execute this action, I encounter an error stating that the function is undefined $(function () { function Example(){ Example1(); } Example1(); }); external.js $(function () { function Example1(){ alert("Hello"); } }); ...

Tips for eliminating the default hover and active states from a textfield in Material UI

Currently, I am in the process of creating a login form and have incorporated Material UI textfields. However, I am facing an issue where the textfield's default hover and active states cannot be removed. Below is my password textfield: (https://i.st ...

Using AngularJS and JavaScript, set the Submit button to be enabled only when the email input is valid and a value is selected in

I'm trying to create a form that includes an email input field and a drop-down list sourced from a database array. Initially, the submit button is disabled when the form loads. My goal is to figure out how to activate the submit button only when the ...

Sails.js: Issue with unintended premature sending of 200 response before desired response is sent

While working with Sails.js version 1.2.3, I encountered an issue where I was unable to send data from a file as a response to a GET request over HTTP or WebSockets. It seems that regardless of whether I access the file synchronously or asynchronously in t ...

Is there a way to incorporate both max-width and min-width in a matchMedia query effectively?

I'm currently utilizing the matchMedia API in my JavaScript code to identify viewports, with the goal of reducing DOM manipulations. Instead of using display: none extensively, I am opting for a v-if directive from Vue to determine when elements are ...

Exploring Unicode in JavaScript to iterate through emojis with different skin tones

Currently, I am facing an issue where Javascript splits emojis with different skin colors into multiple characters instead of treating them as one. Emojis with a yellow skin color work fine and give me the desired results. For example: let emojis = [..." ...

Utilizing pixel values for Material-UI breakpoints rather than using the default sm, md, lg, xl options

Below is the code snippet that I am using: [theme.breakpoints.only('lg')]: {} The above code works perfectly and shifts at the desired breakpoint. However, when I implement the following: [theme.breakpoints.between('1200', '1021&a ...