populate a static div with a monospaced font

Consider a scenario where you have a string of characters and an HTML div element with a fixed size. How many characters from the string can fit into the div without wrapping when using a monospace font and a specified fixed font size? In addition, is there a way to adjust the font size slightly so that the text takes up the entire width of the container?

JavaScript

var s = "skjhfkjsdhjfksdhjkghskjgh...";

CSS

#c { width:267px; font-size:30px; font-family:monospace }

HTML

<div id="c"></div>

Check out this fiddle for a workaround solution that seems to work but may not be the most optimal: https://jsfiddle.net/6et20853/1/

Answer №1

To get the width of one character, you will need to use .getBoundingClientRect on an element that contains a single monospace character:

oneCharWidth = document.querySelector('#testing').getBoundingClientRect().width;
console.log(oneCharWidth)
<span id="testing" style="font-family: monospace">a</span>

If you want to determine the font size needed for a string of text to fit a container with a fixed size:

var widthOfContainer = 400, // The width of the container in pixels
    textLength = "Hello world!".length, // The text to fit
    testElem = document.querySelector('#testing'),
    widthOfChar,
    fontSize = 100; // Initial guess (exaggerated to find optimal value)

do {
  fontSize--;
  testElem.style.fontSize = fontSize + 'px';
  widthOfChar = testElem.getBoundingClientRect().width;
} while (textLength * widthOfChar > widthOfContainer);

var container = document.querySelector('#container');
container.style.fontSize = fontSize + 'px';

testElem.parentNode.removeChild(testElem); // Remove #testing element
#container {
  border: 1px solid red;
  font-family: monospace;
  width: 400px;
}

#testing {
  font-family: monospace;
}
<div id="container">Hello world!</div>
<span id="testing">a</span>

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

"Using JSoup on an Android app to extract the content within specific HTML tags and display each one on its

Looking for some assistance with an issue I'm experiencing with my HTML code: <li itemprop="something">Text 1</li><li itemprop="something">Text 2</li><li itemprop="something">Text 3</li><li itemprop="something"& ...

Setting the initial stage color in Konva can be done by using the `stage.fill

I'm new to using Konva and I was curious if there is a feature that allows me to change the color of the stage. Currently, it defaults to a bright grey which I'd like to adjust without having to manually add a rectangle and fill it with a differe ...

Using HTML in emails to enhance the visual appeal: a table cell with an image next to a table

I've created an HTML document for a newsletter that I plan to send from Outlook 2013. You can view the HTML code on this JSFiddle link. However, when attempting to send it from Outlook, I noticed that the background color of the TD is crossing the bo ...

Searching for a user's first name and last name in mongoDB and retrieving the entire object

My goal is to locate my users in the database by searching for both their first and last names, and then retrieving the complete object of each user. However, my current code only returns the concatenated `firstName` and `lastName` as `name` along with the ...

Encountered a Next-Auth Error: Unable to fetch data, TypeError: fetch failed within

I've been struggling with a unique issue that I haven't found a solution for in any other forum. My Configuration NextJS: v13.0.3 NextAuth: v4.16.4 npm: v8.19.2 node: v18.12.1 When the Issue Arises This particular error only occurs in the pr ...

Having trouble getting the dropdown button to function properly in my Bootstrap navigation bar implementation

Can anyone help me troubleshoot why the dropdown button is not functioning in my code? I've tried following tutorials and searching for solutions online, but nothing seems to work. Any assistance would be greatly appreciated. <!DOCTYPE html> & ...

What is the process of invoking a Java method through AJAX on a website?

I am trying to figure out how to call the Java method getMessage() from a jar file whenever a button on my webpage is clicked. Can anyone help me achieve this? File name: index.html <!doctype html> <html> <head> <meta charset="utf-8" ...

Applying unique textures to individual sides in Three.js

Here is the code for my textured cube: const textureLoader: TextureLoader = new TextureLoader(); const textureArray: MeshBasicMaterial[] = [ new MeshBasicMaterial({ map: textureLoader.load("./model/front.jpeg") }), new MeshBasicMaterial({ map ...

Begin by positioning flex elements outside of the screen and then animate them into their final

I'm struggling to find the right approach to make this animation work effectively. Currently, I have two elements centered vertically within a flexbox layout. My goal is to animate these elements into their final positions by sliding in from off-scre ...

Performing an HTTP GET Request with HTML/JavaScript and JQuery

I am endeavoring to initiate an HTTP GET request from my HTML page. The backend of the application is constructed using PHP and the Laravel 4 framework (for PHP). The API's backend is functional. I have conducted tests using the curl command in my Ma ...

Utilizing JavaScript to extract an image from one div and seamlessly transfer it into another div

Recently, I came across some HTML code that got me thinking. <Div id=Qimage> <a href="http.wwww.....somehitng"> <img class="postphoto" src=""> </a> </div> <Div id=Limage> <a href="www.designerzblog.com" imageanchor= ...

The behavior of relative paths in Ajax can vary depending on the environment in which it

This website is built using SpringBoot. The URL for the HTML page is . Here is a segment of JavaScript code found on the index page: $(function(){ jQuery.ajax({ contentType:'application/json;charset=UTF-8', type: "POST", url: "getSi ...

What is the process for modifying input text and saving it for future use?

Is it possible to create an input field where users can change their name and have the new string stored as a username? I attempted to achieve this using form, but encountered the following error: Error: Template parse errors: Can't bind to 'form ...

Creating a 3D slider on Owl-carousel 2: A Step-by-Step Guide

I am trying to create a slider using Owl-carousel, but I'm having trouble implementing it. I came across this example https://codepen.io/Webevasion/pen/EPMGQe https://i.stack.imgur.com/KnnaN.jpg However, the code from this example doesn't seem ...

Is it possible to have a variable either inside quotation marks or NULL when checking for case within a string in JavaScript

The challenge lies in titling this particular question, but demonstrating it is quite straightforward. My goal is to include multiple value sets in an SQL insert statement like the following: var sqlInsertString = `INSERT INTO events (url) VALUES` var sqlI ...

Incorporate additional plugins into React-Leaflet for enhanced functionality

I'm currently working on developing a custom component using react-leaflet v2, where I aim to extend a leaflet plugin known as EdgeMarker. Unfortunately, the documentation provided lacks sufficient details on how to accomplish this task. In response, ...

CSS: Aligning content vertically centered

Take a look at the following example: <div class="container"> <div class="box1"></div> <div class="box2"></div> </div> The height of box1 is smaller than that of box2. Is there a way to vertically center box1 w ...

Several validation checks - logic malfunction

I have implemented a validation feature for passwords on a form, but I suspect there may be a logic error in my code that I haven't caught yet (blame it on the coffee machine!). Take a look at the JavaScript below: <script type="text/javascript"& ...

Converting a two-dimensional array into a collection of sparse arrays

How can I transform the array x=[[3,1],[2,2]] into x[3][1]=1 and x[2][2]=1? Is there a way to make this code functional for arrays such as x=[[3,1],[2,12],[3,3]]? ...

What is the best way to prevent the content within a div from being obscured by a sticky element affixed to the bottom of the div?

I am struggling with ensuring that the content in my wrapper does not get cut off by the "view more" div attached to the bottom. The default wrapper cuts off the children, and even when expanded, the issue persists due to CSS problems. In React, the gener ...