Adjust the size of various texts to fit the width of the container

I have a unique challenge with resizing text to fit within specific elements. The texts may vary in length and I want to ensure that the longest line fits perfectly within the container's width.

For example, consider this code snippet:

.container {
  width: 400px;
  border: 1px solid green;
  padding: .5em;
}

.container>div {
  border: 1px dotted gray;
}
<div class="container">
  <div>Lorem ipsum dolor sit amet.</div>
  <div>Lorem ipsum.</div>
  <div>Lorem ipsum dolor sit amet, consetetur sadipscing elitr,<br />sed diam nonumy eirmod tempor invidunt<br />ut labore et dolore magna aliquyam erat, sed diam voluptua.</div>
</div>

This should ideally result in something like this:

https://i.sstatic.net/vPtep.jpg

I've explored using relative font sizing units without success, as manually adjusting the font-size for each child element is not feasible. Additionally, solutions for dynamically scaling text based on viewport size don't apply here due to varying text lengths.

Is there a CSS solution to this problem, or would a JavaScript approach be more appropriate? Considering the complexity of fonts with varying letter sizes, finding a suitable method is crucial.

Answer №1

How about this?

$(document).ready(function() {
  var divEls = $('.container div');
  for(var i=0; i<divEls.length;i++){
    var span = $(divEls[i]).find('span');
    var fontSize = 16;
    while (span.width() < $(divEls[i]).width()) {
      span.css('font-size', fontSize++)
    }
    // wrap if span exceeds div width
    if (span.width() > $(divEls[i]).width()) {
      span.css('white-space', 'pre-wrap');
    }  
  }
  
});
.container {
  width: 400px;
  border: 1px solid green;
  padding: .5em;
}

.container>div {
  border: 1px dotted gray;
  white-space: pre;
}
<div class="container">
  <div><span>Lorem ipsum dolor sit amet.</span></div>
  <div><span>Lorem ipsum.</span></div>
  <div><span>Lorem ipsum dolor sit amet, consetetur sadipscing elitr,<br />sed diam nonumy eirmod tempor invidunt<br />ut labore et dolore magna aliquyam erat, sed diam voluptua .</span></div>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

You can also try an ES6 solution like this CodePen Demo


Update - per the comment below, here is a reponsive solution (also see this CodePen Demo):

function resizeFont() {
  var divEls = $(".container div");
  for (var i = 0; i < divEls.length; i++) {
    var span = $(divEls[i]).find("span");
    var fontSize = (span.css("font-size").match(/\d+/)[0]);
    while (span.width() < $(divEls[i]).width()) {
      span.css("font-size", fontSize++);
    }
    while (span.width() > $(divEls[i]).width()) {
      span.css("font-size", fontSize--);
    }
  }
}

$(document).ready(function() {
  resizeFont();
  $(window).on("resize", resizeFont);
});
body {
  margin: 0;
}

.container {
  max-width: 100vw;
  border: 1px solid green;
  padding: .5em;
}

.container>div {
  border: 1px dotted gray;
  white-space: pre;
}
<div class="container">
  <div><span>Lorem ipsum dolor sit amet.</span></div>
  <div><span>Lorem ipsum.</span></div>
  <div><span>Lorem ipsum dolor sit amet, consetetur sadipscing elitr,<br />sed diam nonumy eirmod tempor invidunt<br />ut labore et dolore magna aliquyam erat, sed diam voluptua .</span></div>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

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

React and Redux are throwing an error stating that actions must be simple objects. For any asynchronous actions, it is recommended to utilize

Below is the code for my Component UserHandler import React, { Component } from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import * as actionCreators from '../../store/actions/ac ...

Tips for creating JSON using AngularJs to store tabular information

I successfully created an HTML page using AngularJS. <form name="target" ng-submit="createAllKeywordsJSON(codeMasterList)"><!-- createAllKeywordsJSON() --> <input type="submit" value="Save" class="myButton" name="submit" style="margin: ...

Encountering a typescript error: Attempting to access [key] in an unsafe manner on an object of

I have recently developed a thorough equality checking function. However, I am encountering an issue with the highlighted lines in my code. Does anyone have any suggestions on how to rectify this problem (or perhaps explain what the error signifies)? Her ...

Track changes and save only the updated elements in an array

Currently, I am utilizing Angular for the front end, C# for the backend, and an Oracle database for a project with a company. Within the grids provided to me, there are more than 120 records that users can edit individually. My dilemma lies in identifyin ...

The CSS Scroll-Snapping feature seems to be overlooking one specific element that it should be snapping to

Currently, this website is designed to work exclusively for mobile devices. When viewed in Chrome's mobile view using the inspector, everything appears to be functioning correctly. However, when accessed through Safari or on an actual mobile phone, th ...

Updating parameter value upon the execution of an internal function in Javascript

How can I log the text from a textbox to the console when a button is clicked in this code snippet? <body> <input type="text" id="ttb_text" /> <script type="text/javascript"> function AppendButton() { var _text = ''; ...

Steps to vertically shift an image downwards within a navigation bar using HTML and CSS

Currently, there is a fully functional navigation menu that can be toggled within a webpage. An image is also included in the navigation menu and positioned below the text. I would like to move the image to the very bottom of the navigation menu to remove ...

CSS hover effect: altering background colors of both parent and child elements simultaneously

HTML: <div class="container"> <div class="parent">one <div class="child">two</div> </div> </div> CSS: .parent { background: red; height: 200px; width: 200px; } .child { back ...

The React Navbar dropdown items appear to be displaying only text, without any menu showing up behind

I'm having an issue with the background of my dropdown menu not showing properly. The text within the dropdown items is appearing without a background, making it look like they are floating in a line on the page. I've tried adjusting the z-index ...

Tips on displaying a progress bar with a percentage for a form submission containing a sizeable base64 encoded image

When a form with a base64 encoded image is submitted, there is a delay in uploading the image. The progress can be seen in Chrome at the bottom left corner as "Uploading(x%).. https://i.sstatic.net/Ju6jA.jpg <form id="resizeImageForm" action="resizeIma ...

What are the steps to achieve such a design?

Can you show me how to create a single layout using HTML and CSS? I am struggling with splitting the screen properly. Could you provide a simple example, maybe on jsfiddle? https://i.stack.imgur.com/d2rbn.jpg Thank you in advance! EDIT: I have added a ...

Limit the number of elements in an Angular object by using the filter function

I've implemented an angularjs filter method on a repeated array of items in an attempt to filter numbers using a limitTo filter. However, the result is not reflecting in the DOM. Below is the html code snippet: <div ng-controller="demo as d"> ...

What differences occur in JavaScript when the IE Developers Tools are accessed?

When the IE Developers Tools are opened, what changes in terms of running an AJAX application? I am currently investigating a mysterious bug related to PrimeFaces dropdown lists in Internet Explorer. Sometimes these dropdowns do not open when clicked, but ...

What is a different way to rearrange items within an Angular Controller without relying on orderBy in the HTML?

http://plnkr.co/edit/apwAQG9tczOUckbc9bya?p=preview https://i.sstatic.net/NcNYh.png Seeking to rearrange li elements in the plnkr above without using ng-repeat | orderBy:predicate:reverse syntax in the markup. The challenge is that new items are dynamic ...

JavaScript XML Serialization: Transforming Data into Strings

When trying to consume XML in an Express server using express-xml-bodyparser, the resulting object is not very useful. This is the XML: <SubClass code="A07.0"/> <SubClass code="A07.1"/> <SubClass code="A07.2"/> <SubClass code="A07.3" ...

Having difficulty uploading files to my website [PHP]

I'm having trouble with a PHP tutorial I followed for uploading an image. Despite my best efforts, the upload always fails and I can't figure out why. I've rewritten the code multiple times but the problem persists. The goal of this code is ...

Arranging elements within a complex div structure

I have been working on styling this div that displays the products for an e-commerce website. I initially used CSS and a table within it, but it seems like using tables for content is not recommended, so I am trying to find a better solution. However, my a ...

``There seems to be an issue with VueJs v-for loop not updating

Having an issue with a form where buttons to add children inputs stop working after adding one child. There seems to be an error in the console, but when checking the data output it appears the new input box is being added. The DOM just isn't updating ...

Combining the elements within an array of integers

Can anyone provide insight on how to sum the contents of an integer array using a for loop? I seem to be stuck with my current logic. Below is the code I've been working on: <p id='para'></p> var someArray = [1,2,3,4,5]; funct ...

"Headers cannot be set once they have been sent to the client... Error handling for unhandled promise rejection

Having trouble with cookies in the header - specifically, encountering an error at line number 30. The error message reads: "Cannot set headers after they are sent to the client." Additionally, there is an UnhandledPromiseRejectionWarning related to a prom ...