What is the best way to adjust the font size in CSS/JS so that it creates a specific margin on the sides of its container?

Is it possible to create a font size that is perfectly scaled to fit within a specific container? For example, I would like the text to have 8% margin on each side of the container, and fill the remaining 84%. How can this be achieved using HTML/JS/CSS?

body {
  font-size: 70vh;
  display: flex;
  text-align: center;
  justify-content: center;
}
hello

Answer №1

This method may not yield pixel-perfect results, but it provides an approximate outcome.
By enclosing the text within a <span> tag, you can determine the initial text width and font size, which are essential for calculating the final font size based on the container's width.

window.addEventListener('resize', adjustFontSize);

var textElement = document.querySelector('span'),
textParent = textElement.parentNode,
fontSize = parseFloat(window.getComputedStyle(textElement, null).getPropertyValue('font-size')),
textWidth = textElement.clientWidth,
remainingSpace;

function adjustFontSize() {
  remainingSpace = textParent.clientWidth;
  textElement.style.fontSize = (remainingSpace * fontSize)/textWidth + "px";
}

adjustFontSize();
html {
  background-color: #fff;
}
body {
  background-color: #f3f3f3;
  display: flex;
  text-align: center;
  justify-content: center;
  margin: 0 8%;
}
<body>
  <span>hello</span>
</body>

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

Utilize SCSS values within TypeScript by applying them on a class level

let changeClassDisplay = document.getElementsByClassName('sidebar'); for (var i = 0; i < changeClassDisplay.length; i += 1) { changeClassDisplay[i].style.display = 'block'; } I encountered an issue with this code whe ...

Unable to send multiple cookies using custom headers in Next.js configuration

I am using custom headers to set the cookie in my next.config.js file. The refresh token is successfully set, but for some reason the second token is not being recognized. key: 'Set-Cookie', value: `RefreshTokenKey = " ...

Select2 version 4.0.3 encountering issues when trying to automatically populate additional select2 fields with data fetched through ajax

I'm encountering an issue with Select2. Essentially, I need to populate other form fields with data retrieved from Select2's Ajax search. Even after following an example found here: Select2 4.0 - Push new entry after creation I'm still un ...

problems arising from the alignment of floating divs

I am struggling with aligning the image "logo.jpg" in a left-floated div. How can I center it both vertically and horizontally within the code below? Thank you. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtm ...

Transform the JavaScript onclick function into jQuery

I have been working on incorporating my javascript function into jQuery. The functionality I am aiming for is that when you click on a text (legend_tag), it should get added to the textarea (cartlist). <textarea id="cartlist"></textarea& ...

Provide an instance of mockClient for AWS SQSClient in a TypeScript class

I'm currently working on unit testing a piece of code that relies on a constructor with an SQSClient object for interacting with an sqs queue. To write effective unit tests, I need to mock the client so that I can test the code without actually access ...

What is the process for setting an AMP-video as a full-page background?

My homepage features a captivating hero video in the background, but I've encountered an issue where the AMP video does not scale properly to fit the screen on mobile devices. Here's the code snippet causing the problem: <amp-v ...

Ways to retrieve JSON data through multiple levels of nested if statements

Currently, I am using CodeIgniter to work on a small project involving creating batch lists. When an admin attempts to create a new batch list, they must input the start date, end date, start time, and end time. The system will then check the database to s ...

What's the best way to add a border of 1 pixel solid #ddd to a select box with the help of jQuery?

I'm in need of some assistance, Many websites utilize the jQuery framework to add stylish effects to their selectboxes. Unfortunately, I am limited to using ie7 at my workplace and I want to include a 1px solid #ddd border around my selectbox (which ...

Continuously I am being informed that the value is null

Check out this code snippet: var Ribbon = /** @class */ (function () { function Ribbon(svg) { // Code here... } Ribbon.prototype.init = function() { // Initialization code here... }; Ribbon.prototype.updateR ...

Border shifts on hover effect

After much trial and error, I finally managed to center two links in a nav bar perfectly on the page. I also added a grey bottom border that spans the entire width of the page, with the hover effect turning it blue under the links. Check out this example: ...

The PHP function is returning an undefined value in JavaScript

I feel like there must be a simple solution to this problem that I just can't seem to find. Everything related to PHP search functions and queries is functioning properly, except for the fact that the data isn't displaying correctly in the text a ...

The API for /api/campaign/dynamicid has been resolved but no response was sent, potentially causing delays in processing requests within Next.js

Encountering a problem with my Amazon SES code in Next.js. Unsure where the mistake lies, seeking assistance to resolve the error. Feel free to ask if you have any questions. sendmail.js This is where I encountered an issue in the sendmail.js file while ...

Warning: React JS encountered errors with propType validation and uncontrolled input handling

I've been encountering challenges with React JS and trying to enhance the todoList after completing a crash course. Despite spending 8 hours troubleshooting, I'm still struggling. Hopefully, seeking assistance here will provide me with a fresh pe ...

Loading images in advance with AJAX for enhanced AJAX performance

My website is structured in a sequential manner, where page1.html leads to page2.html and so on. I am looking to preload some images from the third page onto the second page. After searching, I came across this amazing code snippet: $.ajax({ url ...

What can Cordova and express js bring to the table together?

I'm feeling pretty lost when it comes to displaying express views in a Cordova app client. It seems like the app would have to send a GET request and then the express application would render the view. But I'm unsure about how to actually make t ...

Tips on successfully executing the swap method in the JustSwap smart contract

I'm attempting to finalize the JustSwap-contract S-USDT-TRX Token (TQn9Y2khEsLJW1ChVWFMSMeRDow5KcbLSE), but I keep receiving a "REVERT opcode executed" response in the console. My code: const TronWeb = require("tronweb"); const ethers ...

Is it possible to string together requests in a Vue method?

Whenever a user clicks on a specific button, a request is sent to the server and an answer is received. If the user clicks on this button 100 times, I want to send 100 consecutive requests to the server. Each request must be sent after the previous one, as ...

There was a problem with the WebSocket handshake: the response header value for 'Sec-WebSocket-Protocol' did not match any of the values sent

I've encountered an issue with my React project that involves streaming live video through a WebSocket. Whenever the camera firmware is updated, I face an error in establishing the WebSocket connection. Here's how I initiate the WebSocket: wsRe ...

Tips for ensuring elements within a modal receive immediate focus when opened in Angular 2

I am relatively new to Angular JS and I am encountering some challenges with implementing a directive in Angular 2 that can manage focusing on the modal when it is opened by clicking a button. There have been similar queries in the past, with solutions pr ...