Using fit-content with dynamic font size in CSS: How does it work?

Let's take a look at this div element :

    <div style="
            text-align      : center;
            font-size       : min(calc(var(--fp-title-font-ratio-h) *100vh),calc(var(--fp-title-font-ratio-w) *100vw));
            color           : var(--brand-color);
            background      : rgba(0,0,0,0.0);
            margin-top      : 0px;
            z-index         : 500;
            width           : fit-content;
            left            : calc(var(--fp-title-left-ratio-h) * 100vw - (var(--fp-title-left-ratio-w) * 100vw));
            transform       : translateX(0%);
            position        : absolute;
            border-radius   : 10px;
            text-align      : left;
            font-family     : 'Playfair Display', serif;
            text-shadow     : 1px 1px 2px #040b0a,  0 0 0.2em #040b0a;
            ">
        MY TEXT IS VERY LONG ABCDEFGH
    </div>

All the variables are set. When the page loads, the div initially fits the text properly.

However, the font size is updated afterward. Ideally, I would expect the font size to be calculated before rendering the text so that the div adjusts accordingly. Instead, it seems that the font size change occurs after the div has already expanded.

The issue lies in the fact that despite using width:fit-content, the text breaks and wraps to a new line. This behavior can be observed in both Firefox (even with width:-moz-fit-content) and Chromium browsers.

Query:

How can I make sure that the div fits the content after applying the CSS-defined font size?

Note: The problem becomes evident when the screen size is set to 1920x1080.

Potential Solution Attempted:

Trying out display:inline or display:inline-block did not yield any results. While I know this could be fixed later using JavaScript, I am hoping for a pure CSS solution without relying on JavaScript. Is there a way within CSS to address this issue effectively?

Thank you.

Answer №1

Using only CSS might not achieve this effect, but here's a sample utilizing JavaScript:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Adjusting Width Dynamically</title>
    <style>
        div {
            text-align: center;
            font-size: min(calc(var(--fp-title-font-ratio-h) * 100vh), calc(var(--fp-title-font-ratio-w) * 100vw));
            width: auto; 
            white-space: nowrap; 
        }
    </style>
</head>
<body>
    <div id="myDiv">
        MY TEXT IS VERY LONG ABCDEFGH
    </div>

    <script>
        // Fetch the div element
        const div = document.getElementById("myDiv");

        // Calculate the font size
        const fontSize = Math.min(
            parseFloat(getComputedStyle(div).getPropertyValue("--fp-title-font-ratio-h")) * window.innerHeight,
            parseFloat(getComputedStyle(div).getPropertyValue("--fp-title-font-ratio-w")) * window.innerWidth
        );

        // Set the font size
        div.style.fontSize = fontSize + "px";

        // Adjust the width to fit the content after setting the font size
        div.style.width = "fit-content";
    </script>
</body>
</html>

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

Changing the minimum value in an input type number with AngularJS

I am struggling to ensure that the minimum value for an input text box "number" is set to 1. I have a button that decrements it using AngularJS, but even with min="1" specified, the value goes below 1 when clicking the button. How can I maintain the minimu ...

Align the h1 vertically within a div without any extra space around it

I am trying to vertically center my content div within my header div without any extra space around it. I had it working before but the width of the content div would always be 100%. Here is the code I used: #header { position: absolute; width: 100% ...

File index with Node.js server for handling files

I currently have a code snippet for setting up a file server that serves files from a static folder named "public1". However, I am facing difficulties in making an HTML page display by default when a user navigates to the IP address in a browser. Although ...

Struggling to create horizontal buttons for my design

Does anyone have any suggestions for fixing my navigation bar? I attempted to create it myself, but I'm struggling to make everything function properly. https://i.stack.imgur.com/h4yA1.jpg Below are the images of the button in all three states: htt ...

What is the best way to avoid having multiple files in a JavaScript file input when a user selects a new file?

I am trying to implement a file input using vanilla JavaScript, and my goal is to restrict the user to uploading only a single file at a time. The issue I am facing is that if the user repeatedly selects a file and clicks the upload button, the file gets ...

Viewing the details of a checkbox option

I have encountered a situation where I need to handle detail rows within a table that contain checkboxes for selection. The desired behavior is: 1) When clicking on the detail row image, it should expand to show the details of its parent row without sele ...

Tips on showing a success notification following form submission in HTML

I have crafted this code utilizing a combination of bootstrap, python, and html. I have omitted the css portion for brevity, but I can certainly provide it if necessary. My aim is to be able to send an email using smtplib and flask, with the added function ...

Manipulating CSS rules using JavaScript/jQuery

My goal is to create a function that generates a grid based on table data. While the function itself seems to be working, I am encountering an issue where the classes applied are not resulting in any style changes. Below is a snippet of my function: $(doc ...

Angular for user authentication page

I've been busy working on the login page, and I've managed to create a login UI that meets the requirements. However, I'm facing some challenges when it comes to validating the username and password. Being new to Angular and Web API, I might ...

optimal application of css with jquery

I have a question about using jQuery to set the padding of a class or id. I am able to successfully change the height of an element with this code: $('.menu').css({ height: '90px' }); But now, I need to apply a specific CSS rule in jQ ...

In React, CSS @media queries are specifically designed to function only within the Device Mode of Developer Tools

As indicated by the title, I have designed a responsive web app using the React framework along with various @media queries. When I resize the page in Developer Tools' Device Mode, the queries work perfectly fine and everything functions as expected. ...

Is it advisable to set the html root at 62.5% when using rem units in CSS? Does this imply that the default font size of browsers is 16px?

During a discussion with a group, I mentioned the 62.5% trick for scalability (setting 62.5% as font size in root and using rem units throughout CSS for easier scalability when users change default browser font size) and their arguments were as follows: " ...

Styling Angular2 Material Dialog: the perfect fit

The Angular2 material team recently unveiled the MDDialog module at https://github.com/angular/material2/blob/master/src/lib/dialog/README.md I am interested in customizing the appearance of Angular2 material's dialog. Specifically, I want to adjust ...

What causes the element to load with a transparent appearance? And why is my JavaScript code overriding the hover effect on it?

My goal is to have an element fade out when clicked and then fade back in when its space is clicked again. I also want the opacity of the element to be 0.9 instead of 1 when visible. I've encountered two issues with my code. First, the hover selector ...

Div failing to expand to fit its contents

I'm having trouble getting my info-container div to adjust its height based on its contents. I suspect that the floating div within it might be causing the issue, but I'm not certain. I've included a link to jsfiddle where you can view the C ...

increased space between tables in HTML email design for optimal display in Gmail inbox

Here is the link to my code: http://jsfiddle.net/user1212/G86KE/4/ I am experiencing an issue in Gmail where there is extra white space between 2 tables inside the same cell. I have attempted using display:block; margin:0; padding:0; line-height:0; How ...

Issue with data transfer between parent and child components in ReactJS

Currently, I'm in the process of developing my own version of a Trello Clone. The journey has been smooth so far, and I owe much of it to the generous support I've received from everyone here - thank you! However, I've run into a slight roa ...

Visualizing live data streaming from MySQL

I am currently using this code to retrieve values from a database and create a basic line graph (showing response time to an alert vs. UTC time). Everything works smoothly when the data is static, but now I want to try retrieving the data in "real-time" (j ...

Safari displaying incorrect sizing for table nested in inline-flex container

When a <table> is placed within an inline-flex container that has a flex-direction of column, Safari displays the table with a different cross-size compared to Chrome and Firefox. This discrepancy makes me question if Safari's default display fo ...

Angular Material Toolbar Experiencing Color Distortion

To see the issue in action, check out this CodePen: An ongoing problem I've encountered with Angular Material involves distorted colors on the toolbar. The edges of the toolbar display one shade of green, while the middle shows a different shade. Tak ...