Achieve a Dynamic Font Style Inside the Parent Div's Border

Here is an example of an HTML element:

<div id="myid_templates_preview_text_1" style="transform: rotate(0deg); border: 1px solid rgb(0, 0, 0); position: absolute; left: 64.5px; top: 144.984px; width: 117px; height: 42px; z-index: 1;">
    <p>
        <span style="color: #000000; font-size: large;">Sample Very Very Long Line Of Text.</span>
    </p>
</div>

Shown below is the output:

https://i.sstatic.net/y4YCK.png

I would like to adjust the text font size so it does not go beyond the borders of the div. How can I achieve this?

UPDATE 1:

I am currently working on a layout designer application and therefore cannot modify the HTML structure provided above. The user dynamically designs the HTML content. Below is another example of HTML structure.

<div id="myid_templates_preview_text_2" style="transform: rotate(0deg); border: 1px solid rgb(0, 0, 0); position: absolute; left: 62px; top: 84px; width: 87px; height: 97px; z-index: 1;">
    <p style="text-align: center;">
       <span style="font-size: medium;">
           <strong>Sample Very Very Long Line Of Text.</strong>
       </span>
    </p>
    <p style="text-align: center;">
        <span style="font-size: small;">
            <strong>Sample Very Very Long Line Of Text.</strong>
        </span>
    </p>
</div>

https://i.sstatic.net/V9jOk.png

Answer №1

One option, although not the most efficient or ideal method, is to iteratively adjust the font size until it fits within the designated space. I have made some slight modifications to your code for better readability:

#myid_templates_preview_text_1{
  transform: rotate(0deg); 
  border: 1px solid rgb(0, 0, 0); 
  position: absolute; 
  left: 64.5px; 
  top: 144.984px; 
  width: 117px; 
  height: 42px; 
  z-index: 1;
}

#myid_templates_preview_text_1 span{
  color: #000000; 
  font-size: large;
}

.

<div id="myid_templates_preview_text_1">
    <span>Sample Very Very Long Line Of Text.</span>
</div>

Here is the revised code segment:

function adjustTextSize(){
    var wrapper = $('#myid_templates_preview_text_1');
    var containerHeight = wrapper.height(); 
    var textElement = wrapper.find('span').first();
    var textHeight = textElement.height();

    if (textHeight > containerHeight){
        // Text still too big
        var fontSize = parseInt(textElement.css('font-size'));
        if (isNaN(fontSize)) fontSize = 32; 
        fontSize--;
        textElement.css('font-size',fontSize);
        adjustTextSize(); 
    }
}

$(function(){
    adjustTextSize();
});

View the working jsfiddle here: https://jsfiddle.net/8boxt0xk/

UPDATE 1:

If you are unable to modify the markup, you can use this updated function that resizes fonts while maintaining proportions. It is recommended to add margin: 0 to your p tags for a better fit within the div:

function adjustTextSize(){
    var wrapper = $('#myid_templates_preview_text_2');
    var containerHeight = wrapper.height();
    var totalTextHeight = 0;

    wrapper.find('p').each(function(){
        totalTextHeight += $(this).height();
    });

    console.log(containerHeight, totalTextHeight);
    if (totalTextHeight > containerHeight){
        // Text overflow
        wrapper.find('span').each(function(){
           var element = $(this);
           var currentFontSize = parseInt(element.css('font-size'));
           if (isNaN(currentFontSize)) currentFontSize = 28;
           currentFontSize--;
           element.css('font-size', currentFontSize);
        });
        debugger;
        adjustTextSize();  
    }
}

Updated jsfiddle: https://jsfiddle.net/8boxt0xk/2/

Answer №2

Simply make adjustments to the width and height:

<div id="myid_templates_preview_text_1" style="transform: rotate(0deg); border: 1px solid rgb(0, 0, 0); position: absolute; left: 64.5px; top: 144.984px; width: 117px; height: 80px; z-index: 1;">
    <p>
        <span style="color: #000000; font-size: large;">Example Very Long Line Of Text.</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

Attempting to execute a PHP script through a JavaScript if statement

I have a form that requires validation with JavaScript. In one of the if statements, after all other conditions have been validated, I want to execute my PHP script that updates an SQL database with one of the passwords. Here is the final validation code: ...

Creating a variable name from a string using a function

I am creating a log to keep track of the functions that are called. One specific function I am using is record_activity( function_name ); I find it tedious to manually add this at the beginning of every function I want to monitor. Currently, my functions ...

Here is a step-by-step guide on creating a navigation bar with a Login and Sign Up button using Bootstrap 4

I am in the process of creating a navigation bar in bootstrap 4, which includes Login and Sign Up buttons. To get a clear idea of what I'm aiming for, please refer to the images below: https://i.sstatic.net/ibZKa.png https://i.sstatic.net/OUWsX.png ...

What is the technique for integrating a required file into an Angular module using Browserify?

My Angular SPA build is set up to use NPM for calling the browserify script to bundle it. To execute the build process from the terminal, you can run npm run build:js, which triggers the following script in the package.json file: "build:js": "browserify - ...

Struggling to apply the active class using a combination of jquery, nodejs, express, and bootstrap

I've been working on an express generator Node.js application that uses Bootstrap and Jade. I'm facing issues with setting the active state of the navigation bar. After trying to implement some jQuery, I noticed that when I click on the nav bar, ...

Create a duplicate of the sapUI5 JSON model and end the data binding process

I've encountered a similar issue, but the solution doesn't seem to work for me. I have a JSON model named "data" that represents a SAPUi5 form with comboboxes. My goal is to capture the initial state of the model when the application is first ope ...

Should I consider implementing Flexbox even if I need to cater to users still using IE9?

Currently, I am embarking on a fresh project centered around constructing a chat window. Typically, I would readily employ Flexbox for this endeavor; nevertheless, one of the stipulations for this project is to ensure compatibility with IE9. While I under ...

Could PHP possibly recall colors?

I am in the process of developing a website where users can draw on a canvas and convert it into a GIF. I have been successful so far, but I am encountering issues with colors. Let me explain how my website functions: 1) The user draws on the canvas and e ...

Extract ID for Bootstrap modal display

In my project, I am using a bootstrap modal that displays various strings. The challenge I am facing involves a loop of cards, each with a distinct 'id'. When triggering the modal, I want to show the corresponding id inside the modal itself, whic ...

Unresolved issue with AngularJS radio button binding

As a beginner in using Angular.js, I encountered an issue with data binding when dealing with radio buttons. The HTML code in question is: <label class="options_box" ng-repeat="item in item_config_list.item_config"> <input type="radio" name ...

Using JavaScript to enhance and highlight specific items in a dropdown menu

I am looking for a solution to prevent duplicate selections in multiple select dropdowns. I want to alert the user if they have chosen the same value in more than one dropdown. Should I assign different IDs to each dropdown or is it possible to use just on ...

Accessing data from a CD-ROM or DVD through a web browser

I am currently working on developing a web application for a friend that will enable users to simply click a button to upload all the content from the CD-ROM or DVD they have inserted directly to a server. It's not feasible to rely on the standard br ...

There is no Api.js file in the Cordova iOS platform

I have been attempting to integrate the iOS platform into a new Cordova 7.0.1 project, but I continuously encounter the error mentioned in the title of this post. Despite following the steps outlined in this thread here, including removing and re-adding ...

As I go through the database, I notice that my div model functions correctly for the initial record but does not work for any subsequent ones

I came across a model on w3 schools that fits my requirements, but I am facing an issue where the model only works for the first result when looping through my database. It's likely related to the JavaScript code, but I lack experience in this area. C ...

Enhance the performance of ng-class in AngularJS when using ng-repeat with large datasets

I'm currently developing a project using angularJS. My goal is to display a specific part of the data within the main json dataset, which contains around 5000 to 9000 lines, on the view using ng-repeat. There's a table data tag that shows checkbo ...

Is it possible to apply a CSS transition to a div when hovering over a specific area of the

Allow me to elaborate on the current project I am working on. I am in the process of creating an index on a website that is contained within a div element positioned off-screen using CSS margins, with only a portion of it visible. When you hover over the v ...

Browsing through different backdrop visuals

I realize this question has been brought up numerous times before, but I urge you to take a moment and read through it. Currently, I am looking to add more interactivity to my HTML page. My goal is to change the background image every five seconds with a ...

manipulating and ordering JSON array objects in JavaScript

Currently experimenting with json objects in javascript and looking for assistance with a specific issue The json file I have consists of hash objects containing an ID key and an array value [ ipaddress, timestamp, url] For example: {"output": { ...

It is impossible for Javascript to access an element that has been loaded using

After loading a div with PHP, I am attempting to access it from HTML using Javascript. However, when trying to get the element by its id, it keeps alerting as undefined. <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/j ...

Adjusting a NodeJS module for easier integration into codebases

I have organized some functions in a file within a node module structure... Here are the files and folder structure I created: - package.json - README.md - LICENSE.md - code |_______ code.js Currently, to use these functions, I include them like th ...