Adjustable Font Size for consistent width and height dimensions

I am looking to style my <p> elements with a fluid font size while maintaining fixed width and height.

Current Code:

CSS:

p{
    width:500px;
    height:100px;
    background-color:#F0F0F0;
    margin:10px;
    padding:5px;
    font-size:24px;
}

HTML:

<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis pharetra quis dui a laoreet. Proin nibh dolor, faucibus sit amet aliquet ac, varius id eros. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis pharetra quis dui a laoreet. Proin nibh dolor, faucibus sit amet aliquet ac, varius id eros. consectetur adipiscing elit. Duis pharetra quis dui a laoreet. Proin nibh dolor, faucibus sit amet aliquet ac, varius id eros.</p>
<br><br><br>
<br><br><br>

<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis pharetra quis dui a laoreet. Proin nibh dolor, faucibus sit amet aliquet ac, varius id eros, faucibus sit amet aliquet ac, varius id eros.</p>
<br><br><br>

<!-- This one is perfect -->
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis pharetra quis dui a laoreet. Proin nibh dolor, faucibus sit amet aliquet ac, varius id eros.</p>

Try the code out on jsfiddle:

http://jsfiddle.net/8GNAV/

The desired output can be seen here:

http://jsfiddle.net/8GNAV/1/

Answer №1

The basic concept involves setting the CSS property overflow:hidden, then gradually reducing the font size until the content can fit without scrolling. Here's how it works:

[].forEach.call(document.getElementsByTagName('p'),function(p) {
  p.style.overflow = "hidden";
  var fontSize = 24;
  while(fontSize > 6 && p.scrollHeight > p.offsetHeight) {
    fontSize--;
    p.style.fontSize = fontSize+"px";
  }
});

Check out the live demo here

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

What makes Javascript's Math.floor the least efficient method for calculating floor values in Javascript?

Typically, I'm not a big fan of microbenchmarks. However, this particular one unveils a fascinating revelation. The findings suggest that using Math.floor is actually the SLOWEST method for calculating floor in Javascript. Surprisingly, ~~n, n|n, and ...

Is there a way to use jQuery to adjust the text color once it has been clicked on?

I have been struggling to change the text color upon clicking on it without any success. Within my code, there are seven labels - one for the question, four for the answer options, one for the correct answer, and the last one for the explanation. The desi ...

Reset vue input fields after triggering event

I'm facing an issue with my Vue component that has an input and a button. I want the button to send the input data elsewhere and then clear the input field, but it's not working as expected. Below is a basic runnable version of what I currently ...

Utilizing Angular to make API requests and handle promises

Currently, I am facing a challenge in my angular application which involves working with the soundcloud api. The issue arises when I make a call to the soundcloud api to retrieve my tracks, loop through them to extract the iframe embed object, inject it in ...

Every time the attribute of the Angular controller changes, it is reinitialized

I'm currently in the process of developing a single page application using angularjs 1 and ngRoute, and I've encountered an issue. Within a view (/posts) I have a controller (PostsController) with an attribute called 'posts' that holds ...

Tips for implementing Angular date filter once a REST call is successful or after an event broadcast has been triggered

One challenge I'm facing involves using a REST API to retrieve date formatting information that is crucial for my custom date filter in Angular. My goal is to seamlessly integrate this date format into my view by utilizing the filter. In my view, I h ...

What resources are available for integrating Breeze JS with Rails?

Searching for an efficient REST API management adapter for AngularJS that seamlessly integrates with my Rails backend has been quite challenging. I require a solution that can handle client-side caching, lookups, and Object Relational Mapping (ORM) effortl ...

Struggling to chart out a series of outcomes in react js with no success

I am currently working on creating a YouTube app using React and the YouTube v3 API. After fetching the data with Axios, I am facing an issue while trying to map the data. Can anyone provide some assistance? import React,{useState,useEffect ...

When clicking, populate the content of another div in a vertical top-to-bottom fashion

I am in the process of creating a functionality where clicking on one element will fill another element's content from bottom to top. Although I have managed to make it work on hover, the same functionality is not triggered when clicking on the eleme ...

Is it possible to retrieve a form in Angular.js as a data structure?

My Objective: The framework I'm currently using generates input names based on a specific convention. Here is an example of the generated input names within my form structure for a scenario where a "Class has many Students": name="data[Class][name]" ...

Developing a unique offset for a polyline in ThreeJS

I am working with a Geometry that has vertices forming a polyline. However, the offset I have created is not accurate. Currently, I am calculating the center of the geometry and then offsetting a value relative to this center. This method is resulting in a ...

Reorganizing a Javascript array

Here is a JavaScript array that I have: var test =[{ Maths:{ ST1:10, ST2:2, ST3:15} }, { Science:{ ST1:50, ST3:40} } ] I need to transform this array into the following format: var t = [{ST1:{ Maths:10, ...

Discover the Names of Elements associated with the identical Input File tag

Having a bit of trouble with my jQuery code here. I've got two HTML input file elements with different names. How can I retrieve the name of the second input file using jQuery? Below is my HTML markup: <input type="file" name="photo_a" /> &l ...

Troubleshooting Mime Type Problem in Multer Library for Node.js

While working on my project, I encountered an issue while trying to upload a Photoshop file using Multer. When specifying the mime type for Photoshop, wave, and mp3 files, I received the following error: Error: Mime type invalid at DiskStorage.destination ...

Alter the placement of two bootstrap rows based on the button that is selected

I have a webpage with two bootstrap rows and two buttons positioned at the top of the screen. I want to achieve a functionality where clicking the second button will bring the second row on top of the first row, and vice versa. Here are my two rows: < ...

Trigger an instantaneous update of the masonry grid

My website currently utilizes a script that generates a grid, and the grid elements are automatically adjusted each time the width of the viewport is modified. Although I do not have access to or control over the script since I did not write it myself, I s ...

The jQuery ajax call is returning some undefined results, which is in contrast to the network response, which appears to be completely accurate

My system utilizes an oracle-db and a php-script that is triggered by a query ajax-call. Here is the php-script: $query = 'SELECT pl.event_id, pl.og2, d.name dst, pl.state, pl.note, pl.createdate FROM publevels pl LEFT JOIN dst d on (d.og2 = pl.og ...

jQuery has identified the JSON object as a string

Currently, I am attempting to extract information from JSON that is received through an AJAX call using jQuery. To be more specific, the JSON is being encoded by PHP and appears as follows: {"1":{"key1":"value1","key2":"value2"},"0":{"key1":"value1","key ...

Running two blocks of scripts (utilizing lab.js as a loading manager)

I am currently facing an issue where I am trying to load two separate blocks of `lab.js` in different locations. However, when I attempt to utilize functions from the second block that are called from files loaded in the first block, they are showing as un ...

"Mastering the art of printing wrapped text with Bootstrap to avoid pesky horizontal scrollbars

My issue is quite straightforward. I am trying to display all content on a web browser without the need for a horizontal scrollbar. <div class="container"> <div class="row h-100" style="overflow-y:scroll; padding-left: ...