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

Issues have been reported with the functionality of the backbone.js app when switching views, particularly regarding the inconsistent

I am in need of assistance with backbone.js. Whenever a 403 or 401 error occurs, I want to display the login view. Currently, I have attempted the following approach: $(document).on('ready', function(){ app.loadTemplates(['ShellView&apo ...

Is there a way to bring in both a variable and a type from a single file in Typescript?

I have some interfaces and an enum being exported in my implementation file. // types/user.ts export enum LoginStatus { Initial = 0, Authorized = 1, NotAuthorized = 2, } export interface UserState { name: string; loginStatus: LoginStatus; }; ex ...

Adjust the vertical alignment in Material UI Grid to allow for proper tab navigation while maintaining the original order

When using Material-UI's standard grid system, the alignment of a new grid item after all 12 "space units" are utilized is based on the longest element within those 12 "space units". Is there a way to disrupt this type of alignment? If you take a look ...

execute the NPM script in the current directory

Within my package.json file for a node project, I have the following test script that utilizes the ts-node package: "scripts": { "build": "tsc", "test": "ts-node" } Executing this script from the root ...

What is the syntax for indenting text inside an inline-block element?

Essentially, the checkboxes displayed here are in a graphical format to avoid using checkbox elements for accessibility reasons (only the link should be interactive). However, aligning a span next to an href and indenting the text to line up with the star ...

magnific popup: trigger the display by clicking on an element other than the image

A recent request from the client calls for the image caption to cover the thumbnail fully when hovered over. To meet this requirement, I now need to enable clicking on the caption to open Magnific Popup rather than using the <a> tag. Here is what I h ...

Tips for establishing a connection to a proxy server and executing an http.request through the proxy using nodejs

I'm looking to establish a connection to a proxy in order to send http requests through it. For instance: proxy.connect(someip:someport,function(){ console.log('[PM]['+this._account+'] Logging in..'); var auth_re = /auth& ...

Submitting a form using jQuery and processing the response

Can a form be submitted using jQuery without utilizing json, ajax, or other methods for handling the result? For example: <form id="loginform"> //some input fields and a submit button. </form> And then with jQuery: $("#loginform").sub ...

Guide on how to compile template strings during the build process with Babel, without using Webpack

I'm currently utilizing Babel for transpiling some ES6 code, excluding Webpack. Within the code, there is a template literal that I wish to evaluate during the build process. The import in the code where I want to inject the version looks like this: ...

The redirect feature in getServerSideProps may not function properly across all pages

Whenever a user visits any page without a token, I want them to be redirected to the /login page. In my _app.js file, I included the following code: export const getServerSideProps = async () => { return { props: {}, redirect: { des ...

Load css and js files from a directory within Liferay

Is it possible to automatically load all CSS (or JS) files from a specific folder in Liferay 6.2? Below is an example of the liferay-portlet.xml file: <portlet> <portlet-name>Example</portlet-name> <icon>/icon.png</icon ...

The useEffect hook is triggering multiple unnecessary calls

Imagine a tree-like structure that needs to be expanded to display all checked children. Check out this piece of code below: const { data } = useGetData(); // a custom react-query hook fetching data from an endpoint Now, there's a function that fin ...

Fading text that gradually vanishes depending on the viewport width... with ellipses!

I currently have a two-item unordered list positioned absolutely to the top right of the viewport. <header id="top-bar"> <ul> <li> <a href="#">David Bowie</a> </li> <li> ...

"Upon updating, the array within the mapped state to props in React Redux appears to be

As I work on updating a user's profile through a form, my goal is to ensure the component rerenders after the update and displays the correct information on the form once saved. Here is what I have implemented so far: ProfileInput.tsx const ProfileI ...

The persistent loading animation in AngularMaterial Autocomplete does not come to an end

Exploring AngularJS and AngularMaterial: Currently, I am delving into the world of AngularJS and experimenting with AngularMaterial. To put it to the test, I decided to create a sample based on the code provided in the documentation (check codepen). My ap ...

How can I adjust the border opacity in a React application?

Can we adjust the border color opacity in React when using a theme color that is imported? For example, if our CSS includes: borderBottomColor: theme.palette.primary.main and we are importing the theme with Material UI using makeStyles, is there a way to ...

How can I retrieve the name of an HTTP status code using JavaScript and AngularJS?

My web application is built using AngularJS, JS, JQ, HTML5, and CSS3. It interacts with our projects' REST API by sending various HTTP methods and manipulating the data received. The functionality is similar to what can be achieved with DHC by Restlet ...

Tips for updating the font color of BarMenu in Blazorise

I am struggling to change the default font color of the bar menu to red in a razor page. Despite trying the code below, it doesn't seem to work: <Bar Breakpoint="Breakpoint.Desktop" Background="Background.Light" ThemeContr ...

"Troubleshooting tip: encountering a SyntaxError message stating 'import declarations may only appear at top level of a module'? Here's

After downloading fetch-jsonp by running npm i fetch-jsonp and adding its dependency to my package.json, I attempted to import it using the following code at the top of my main.js: import fetchJsonp from 'fetch-jsonp'; However, I kept encounter ...

Creating a sleek and stylish panel with a static horizontal table size in Bootstrap 3.0

I'm having trouble with the nested table staying a static large size while the panel decreases as I resize my browser. Any tips on how to fix this? <div class="panel panel-primary"> <table class="table"> ... Here is an exampl ...