Tips for adjusting font size automatically to fit within its parent container every time

On my blog, the post titles are displayed in a div with a video playing in the background. The length of the title varies, ranging from 2 words to over 20 words. When the title is too long, it may overflow from its parent container where the video is playing.

I don't want to cut off the overflowing text or use scrollbars or ellipses "...". What I need is a solution that dynamically resizes the font if the text overflows, ensuring it fits perfectly within its parent div regardless of the viewport size.

For reference, here is the code: https://codepen.io/anon/pen/QgBZqd

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
    <title>SINEMACERA</title>
    ...
</head>
<body>
...

CSS

body {
    background: black;
    color:white;
    font-family: Cabin;
}

...

.container:nth-of-type(2) {
    padding-bottom: 1%;
}

JS

$(".btn-primary").click(function() {
...
});
...

Answer №1

After some tinkering, I stumbled upon a solution for this issue that I had encountered before.

Node.prototype.adjustFontSize = function(maxSize) {
  maxSize = maxSize || 500;
  this.style.whiteSpace = "nowrap";
  this.style.overflow = "scroll";
  this.style.fontSize = maxSize + "px";

  while (this.scrollWidth > this.clientWidth) {
    this.style.fontSize = --maxSize + "px";
  }
}

document.querySelector('.container').adjustFontSize();
<div class="container">
  Text To Fit
</div>

Answer №2

Utilize the `vh` unit in CSS:

font-size: 20vh;

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

Navigating the absence of Prismic's ability to use the <blockquote> element in their rich text editor

My experience with Prismic as a headless CMS has been mostly positive, but I recently encountered an issue that surprised me - the lack of support for a simple blockquote. It's baffling to me that such a basic HTML element is not natively supported by ...

PHP is unable to render Google Maps on the webpage

My PHP code retrieves location information from a database (test) and table named manu, created using phpmyadmin in Wamp. It then displays those locations on a map with markers, showing latitude and longitude values. UPDATED <? $dbname =&ap ...

What is the best way to superimpose text on a variety of images with varying sizes using CSS

I have a client who is requesting a sold text to be displayed on top of all images that have been sold, positioned in the bottom left corner of each image. While I have successfully implemented this feature, the issue arises when dealing with images of var ...

Having trouble understanding how to display an HTML file using Next.JS?

Currently, I am working on a project that involves utilizing Next.JS to develop a webpage. The main goal is to display a PDF file on the left side of the screen while integrating Chaindesk on the right side to create a chat bot capable of extracting inform ...

I encounter a CORS issue on Heroku, but strangely it only occurs after 20 minutes of deploying. Prior to that time frame, everything functions seamlessly

Today, I encountered a strange issue while hosting my first Node JS backend on Heroku. Everything runs smoothly when I register/login immediately after deploying the backend. However, if I try to register/login after about 15 minutes, I start receiving a C ...

"Troubleshooting issues with data loading using React's useEffect function

While working on my project, I encountered a strange issue where the isLoading state is being set to false before the data fetching process is completed. I am using the useEffect hook to show a loading spinner while fetching data from an API, and then disp ...

What are some strategies for disregarding the effects of the !important rule

After incorporating some HTML and CSS styling into a third-party site, I encountered an issue where their styling was conflicting with mine, specifically due to certain !important declarations. I want to avoid this conflict without resorting to using !impo ...

ES6 Promises have a curious ability to accurately retrieve values from custom JavaScript objects

I have developed a unique library that functions independently from the Promise API, yet achieves similar objectives. It utilizes window.requestAnimationFrame and fallbacks to setTimeout, having no similarities with Promises. Interestingly, it is compatibl ...

Using the combination of PHP and AJAX, modify files in real-time

Looking to dynamically change files based on screen resolution, I have three files: index.php main.js testA.php testB.php The index.php file will dynamically call testA and testB. If the screen resolution is desktop size, index.php should include testA ...

Utilize identical animations across various elements

I have a canvas animation in JavaScript that is currently limited to one canvas element with the id "stars". I want to be able to use this animation multiple times without repeating the code. Is there a way to add a class for the canvas elements instead of ...

In angular.js, repeating elements must be unique and duplicates are not permitted

My view controller includes this code snippet for fetching data from an API server: $scope.recent_news_posts = localStorageService.get('recent_news_posts') || []; $http({method: 'GET', url: 'http://myapi.com/posts'} ...

Navigating Modal Pop-ups in Django

My current approach for handling modal windows involves referring to this article here. However, I am struggling with implementing some basic functionality using this method. Within my HTML code, I have the following structure: {% for order in queryset% ...

Is it possible to utilize an API response within a conditional statement in NextJS?

I am working on a change password feature that interacts with an API for verification. If the current password entered is incorrect, I want to display an error message. If you have any suggestions on how to proceed or if there are any flaws in my approach ...

Can you explain the compatibility between comet and PHP?

As I utilize Comet iframe, I simply send script tags from the backend PHP file to the frontend where JavaScript displays them. I would appreciate it if someone could provide a concise explanation of how the comet server fits into the equation and how comm ...

Can the ValidationPipe be utilized with a whiteList on the response body?

How can we prevent the return of certain key values in responses from a NestJs server when using TypeOrm entities? For instance, ensuring that a user's password is never sent to any client: In the user.entity.ts file: @Entity() export class User ext ...

Utilize AJAX to retrieve PHP information through a request

Hello everyone! I'm currently experimenting with using AJAX to retrieve a PHP file and execute some functions. This is how my AJAX code looks: $(document).ready(function(){ $(".claim-button").click(function(){ alert("You clicked okay!"); ...

What are the steps to fix the "Invariant Violation" issue that is linked to the redux store?

During my DOM testing to verify if a dialog box would open upon clicking a button, I encountered an error message: Invariant Violation: Could not find "store" in either the context or props of >"Connect(Photos)". Either wrap the root component in a , or ...

Achieving automatic checkbox selection in Angular 6 through passing a value from one component to another

My page named second.html contains the following code: <div class="col-lg-4 col-md-4 col-sm-4"> <input type="checkbox" class="checkmark" name="nond" [checked]="r=='true'" (change)="nond($event, check)"> ...

Conceal the scroll bar within a div set to 100% viewport

Having some difficulty with a scrollbar on my new portfolio. The layout consists of two columns, with content on the left. I need the ability to scroll without displaying the scrollbar. I attempted the code below but it did not work. Could the issue be rel ...

Using React.js - What is the process for submitting a form automatically when the page loads?

Upon loading the page, I have a form that needs to be displayed. Here is the code snippet: <form name="myform" method="POST" className={classes.root} target="mydiv" action="https://example.com/submit" onLoad= ...