Adjust text to fit within a specified height container automatically

Is there a way to make text resize automatically based on the height and width of its container? I've looked at similar questions but none seem to provide the right solution for me. I tried using fitText, but it doesn't take the container's height into consideration, causing the text to overflow at a certain point. Here is an example of my code:

    <div class="col-sm-6 ms-3 mt-2 video-text-box bg-primary" style="height: 33vh">
        <h4 class="desc-heading">
            We offer a broad range of benefits.
        </h4>
        <p class="desc-text">
               You can <span class="fw-bold">customize</span> a benefits program that's perfect for your needs.
        </p>
        <p class="desc-text">
               Failure to enroll will result in you and your family losing benefit coverage starting January 1, 2023.
        </p>
    </div>

fitText Implementation:

    jQuery(".desc-heading").fitText(1);
    jQuery(".desc-text").fitText(1.3);

Note: Increasing the compressor value too much will make the text very small on tablet screens.

Answer №1

To accomplish this goal, you can utilize a double-wrapping technique along with a custom JavaScript function. It would be beneficial to delve deeper into why considering the width is essential.

$(function () {

    $('#btn_fit_text').on('click', function () {
    fit_text();
  });

});


function fit_text() {
        
    var $outer = $('.outer-container'),
            $inner = $('.inner-container'),
        font_size = parseInt($('.inner-container').css('font-size'));
    
    font_size = Number.isNaN(font_size) ? 16 : font_size;
    
    var is_oversize = $inner.outerHeight() > $outer.outerHeight();
    
    while (is_oversize) {
    
        font_size = parseInt($('.inner-container').css('font-size'));
        is_oversize = $inner.outerHeight() > $outer.outerHeight();
      
      $('.inner-container').css('font-size', (font_size - 1) + 'px');
    
        } 
    
    console.log('SIZE');
    console.log(font_size);
    
}
.outer-container {
  border: 2px solid red;
  width: 200px;
  height: 100px;
}

.inner-container {
  background: skyblue;
  padding: 20px;
}
<script
              src="https://code.jquery.com/jquery-3.6.0.min.js"
              integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="
              crossorigin="anonymous"></script>
<button id="btn_fit_text">
Fit text
</button>

<div class="outer-container">
    <div class="inner-container">
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum sit amet condimentum neque, at porttitor justo. Nunc tellus nulla, egestas et vehicula et, malesuada non libero. Aliquam at libero ipsum. Sed rhoncus augue magna. Nunc bibendum ut purus ut blandit. Nullam pellentesque sapien et tempus hendrerit. Ut eget odio est. Proin ac tempor sapien. 
    </div>
</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

The way jQuery and CSS are rendered in the same browser window can vary depending on whether they are loaded via Django or statically

Experiencing a perplexing dilemma. While viewing a web page created using html, jquery, and css on the same browser but in two separate tabs, I am encountering varying renderings of the page. Scenario 1: Directly loading the html file from the file system ...

Ways to Validate Success Data in jQuery

After successfully calling a PHP function using jQuery, I encountered an issue with the Ajax success function where I am unable to reset the form data upon successful submission. I attempted using the if(data.status == 'success'){ } format as we ...

Issue with 'backface-visibility' CSS3 property not functioning on any versions of Internet Explorer

I'm looking to implement a specific animation in Internet Explorer. The goal is to rotate an image like a coin, displaying a different image on the other side. I suspect that the issue lies with Backface-visibility in IE, but I'm not entirely sur ...

Tips for decreasing the width of an element by one pixel when it is specified in percentage

There are four elements, each with a width of 25%, filling the page perfectly. I am trying to create a 1px gap between each element by adding a margin-right of 1px. However, this causes the last element to overflow onto the next line. How can I reduce the ...

An issue with the font display

I'm having trouble with a specific font on my webpage and jsfiddle, even though it works fine on w3schools website. Here's an example on jsfiddle HTML <div> With CSS3, websites can finally use fonts other than the pre-selected "web-safe" ...

How to dynamically populate a select option with data from a database in CodeIgniter 3 and automatically display the result in a text

How can I fetch select options from a database in CodeIgniter 3 and display the result in a text field and span area? Currently, I am only able to display data from the row_name when an option is selected. Here is my current implementation: <?php $query ...

How to adjust the background picture opacity in HTML

Is it possible to adjust the transparency of a background image in HTML? I came across one solution that involved adding a box on top of the background picture and changing the opacity of the box, which in turn changed the opacity of the background pictur ...

Styling the right button of the split button in jQuery Mobile version 1.4.0 using CSS

I was attempting to create a listview with list items that have a button on the right side, much like a jQuery Mobile split button listview. However, I only want the right button to be clickable. The left part of each item should contain a label along with ...

Reduce the transparency of the overlay picture

I have been utilizing the 'Big Picture' template to design a webpage. The overlay.png file adds a lighter background effect by overlaying intro.jpg with a partially transparent blue graphic. Despite my efforts to adjust the opacity and gradient/R ...

The navigation dropdown menu in Bootstrap 4 spills over the edges of the window

In the code snippet provided above, an example of a navbar with a dropdown menu is given. One issue that arises is when the dropdown menu is clicked and it overflows to the right, causing a horizontal scroll bar to appear on the window. The question at ha ...

Unseen components and columns with Bootstrap 4

I am attempting to hide a checkbox input in the middle of some column elements using Bootstrap 4. <div class="container"> <div class="row"> <a class="col-2"> 1 of 2 </a> <input type="checkbox" class="invisibl ...

What is the Method for Multiplying Two ng-module Values in AngularJS?

In my application, I am utilizing the MEAN stack with AngularJS for the front-end. I have a table that contains two values - 'Payment value' with commas and 'commission' without commas. How can I multiply these two values? For example: ...

Tips for aligning 2 columns when both table cells contain inner tables

Concerning my HTML table, cells #3 and #4 contain inner tables. I am facing an issue with aligning the rows within each table in cell #3 and cell #4 properly. Sometimes, the length of text in a row exceeds a single line, causing misalignment with the othe ...

Encountered a JavaScript error while using Internet Explorer

My web and Jquery plugins are working flawlessly on various browsers such as Firefox, Chrome, Safari (Windows & OSX), and Android. However, they encounter issues with Windows and Internet Explorer as some JavaScript fails to load. It's frustrating tha ...

Adjust the div's height to 0

I need to dynamically set the height of a div element with a height of 34px to 0px. However, this div does not have a specific class or ID, so I can't use traditional DOM manipulation methods like .getElementById(), .getElementByClassName, or .getElem ...

Angular allows for the creation of dynamic and interactive scenes using Canvas and Three.js

I am in the process of developing a collection of web apps within an Angular SPA. Each individual application is encapsulated within an Angular template, and when navigating between them, specific DOM elements are replaced and scripts from controllers are ...

AngularJS does not function upon reloading the browser

I am currently working on a new project that involves the following components: Node.js (v0.10.37) Express micro framework Jade templating engine Angular.js (latest) Material design library (material.angularjs.org) Jquery One issue that I am facing is r ...

Validation of hidden fields in MVC architectureUsing the MVC pattern to

Depending on the selections made in the dropdown menu, certain fields will appear and disappear on the page. For example: <section> @Html.LabelFor(model => model.AuctionTypeId) <div> @Html.DropDownList("AuctionTypeI ...

Using Angular template to embed Animate CC Canvas Export

Looking to incorporate a small animation created in animate cc into an angular template on a canvas as shown below: <div id="animation_container" style="background-color:rgba(255, 255, 255, 1.00); width:1014px; height:650px"> <canvas id="canv ...

The issue of JQuery UI Dialog remaining open even after triggering it through an Input focus event

I am facing an issue with JQuery and JQuery UI. I thought upgrading to the latest stable version would solve it, but unfortunately, that was not the case. I am currently using Chrome. When I initiate the dialog by clicking on a specific element, everythin ...