Is it possible for HTML/CSS to automatically adjust content size to fit or fill a container?

I'm interested in finding a CSS-only technique that can ensure content within a container scales to fit, regardless of whether it's text or images. Take a look at the example below:

.container {
    display: inline-block;
    width: 2in;
    height: 1in;
    font-size: resize-to-container /* <- any suggestions? */
}

<div class="container">Some Text</div>
<div class="container">Another container with considerably 
more content, so the font should shrink to fit</div>

If dealing with images:

.container {
    display: inline-block;
    width: 2in;
    height: 1in;
    overflow: adjust-to-fit /* <- however, not with 'overflow' alone */
}

<div class="container">
 <img src="one.png"/>
</div>

<div class="container">
 <img src="one.png"/>
 <img src="two.png"/>
 <img src="three.png"/>
 <img src="four.png"/>
 <img src="five.png"/>
 <img src="six.png"/>
 <img src="seven.png"/>
 <img src="eight.png"/>
</div>

For a visual demonstration, you can refer to this link. Please note that although this fiddle offers an example, it's not a flawless solution and required unnecessary complexity to achieve the desired effect. Initially, I attempted using SVG by creating the content as a single image and then setting max-width. Unfortunately, this approach failed as it only cropped the image.

I am curious to know if there exists a pure CSS technique that can accomplish this effect seamlessly?

Answer №1

Is it possible to resize the content of a container using only CSS?

In short:

No.

In more detail:

You can adjust the font size in relation to different factors:

  • The viewport width (using vw, vh, vmax, and vmin)
  • The font size of the element itself (using em or %)
  • The font size of the root element (using rem)

It is also possible to scale the font size according to the parent element, but this approach only works if the parent element's size is relative to the viewport.

For example: If the stylesheet contains the following code:

p {
width: 20vw;
font-size: 2vw;
}

The width of the paragraph will always be 20% of the viewport width, and the font size will always be 2% of the viewport width. Therefore, the font size of the paragraph will always be 10% of its width.

Alternatively, you can scale the font size relative to a fixed-width parent element:

For example: If the stylesheet contains the following code:

p {
width: 200px;
font-size: 20px;
}

The font size of the paragraph will always be 10% of its width.

However, there is no unit that allows the font size of a fixed-width element to be inversely proportional to the amount of text it contains.

That being said, you can create a solution using JavaScript:

Here is a quick script that decreases the font size of a div as its textual content increases:

var containers = document.getElementsByClassName('container');

for (var i = 0; i < containers.length; i++) {
var text = containers[i].textContent;

var calculatedFontSize;

switch (true) {
case (text.length < 10) : calculatedFontSize = 50; break;
case (text.length < 20) : calculatedFontSize = 40; break;
case (text.length < 30) : calculatedFontSize = 30; break;
case (text.length < 40) : calculatedFontSize = 24; break;
case (text.length < 50) : calculatedFontSize = 22; break;
case (text.length < 60) : calculatedFontSize = 21; break;
case (text.length < 70) : calculatedFontSize = 20; break;
case (text.length < 80) : calculatedFontSize = 19; break;
case (text.length < 90) : calculatedFontSize = 18; break;
case (text.length < 100) : calculatedFontSize = 17; break;
case (text.length < 110) : calculatedFontSize = 16; break;
case (text.length < 120) : calculatedFontSize = 15; break;
case (text.length < 130) : calculatedFontSize = 14; break;
default : calculatedFontSize = 12; break;
}

containers[i].style.fontSize = calculatedFontSize + 'px';
}
.container {
position: relative;
display: inline-block;
width: 2in;
height: 1in;
margin: 0 6px 6px 0;
background-color: rgb(191,191,191);
vertical-align: top;
}
<div class="container">
Some Text.
</div>

<div class="container">
A little more text.
</div>

<div class="container">
Considerably more text, now something like the size of a sentence.
</div>

<div class="container">
Another container with significantly more content, and so the font should scale down to fit.
</div>

<div class="container">
A fifth container with a very much larger amount of content, which inevitably ends up creating a much longer sentence.
</div>

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 jQuery to refresh a div element

I am struggling with updating the "right" div in my jsp page using the script below. Despite being contained in a single file, the update does not seem to work. Any assistance is appreciated. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//E ...

How can I make a Material UI element fill the entire remaining width of the Grid?

Is there a way to make the child element take up the remaining width of the grid in Material UI? I am trying to have the "User Name" text field fill up the rest of the space in the grid cell but so far I have not been successful. I have even attempted us ...

Changing pricing on pricing table with a click

Looking to implement a price changing button that functions similar to the one found at this LINK: If anyone knows of any JavaScript or other solution, please provide me with some guidance. Thank you in advance. ...

What is the best way to use SQL and Flask to automatically fill out a form based on a selection made from a

Looking for assistance with populating an HTML form by selecting a company from a dropdown menu. The desired result is similar to the example found here, using SQL and Flask. I'm unsure of how to retrieve the selected value from the <option> ta ...

The successful execution of $.ajax does not occur

Starting out with ajax, I wanted to create a simple add operation. Here is the code that I came up with: HTML: <!doctype html> <html> <head> <title>Add two numbers</title> <meta content="text/html;charset=utf-8" h ...

Resizing images in HTML can sometimes lead to extra white space appearing underneath the

I am facing an unusual scaling issue with my website design. Whenever I resize the browser window horizontally, the image scales correctly, but it leaves a white space below it where the rest of the page should start from if the window is large. I'm ...

Is the in-app browser of WeChat able to support self-signed HTTPS URLs?

My local WAMP server hosts a web application with self-signed SSL enabled, resulting in the following app URL: https://myipaddress:port/demoapp/index.html However, when I send this URL via WeChat chat and click on it, only a blank page is displayed. Stra ...

Necessary Quasar Select Dropdown Class

Looking to set an asterisk (*) next to the Select component in Quasar when it is marked as "required". While I can achieve this with the input component, replicating the same behavior for dropdowns has proved challenging. I attempted using the :deep selec ...

In JavaScript, a prompt is used to request the user to input a CSS property. If the input is incorrect,

Implement a while loop that continuously prompts the user to enter a color. If the color entered matches a CSS property such as blue, red, or #000000: The background will change accordingly, but if the user enters an incorrect color, a message will be dis ...

Exploring intricate binding expressions using IF statements in ASP.NET

I am trying to create an expression for a column in my repeater, but I am not confident about the syntax. My goal is to display "No Document" if the value is equal to "DispForm.aspx", otherwise show the actual value. I attempted to combine all expression ...

How can I wrap text in Angular for better readability?

I've created a calendar in my code that displays events for each day. However, some event descriptions are too long and get cut off on the display. Even after attempting to use Word Wrap, I still can't see the full text of these events unless I c ...

Changing the color of a div while implementing a show and hide effect in JavaScript

I have designed a checkout system with three distinct parts - shipping information, billing information, and order confirmation. These sections are all on the same page, allowing for a seamless flow during the checkout process. Once a customer completes t ...

What is the best way to toggle the visibility of a background image within a carousel?

As a beginner in j-query, I am struggling with creating a slider image carousel using a full background image. Most of the solutions I found online require a fixed width for all pictures to slide smoothly. However, I believe there might be a way to use an ...

Struggling to create a line break within an SVG using the <tspan> element?

I have a pair of text lines that are wrapped in <tspan> tags. <tspan dy="-11.7890625">welcome</tspan> <tspan dy="16.8" x="285.75">text</tspan> I am trying to add a line break between them, but the <br> tag is not worki ...

Radio buttons have been concealed and are not visible

Tried the solutions recommended in a previous question about radio buttons not showing in Safari and Chrome, but unfortunately, it did not solve my problem. It seems like this issue is different from the one discussed in that question. The WordPress them ...

Full-width header with scrollable content within the viewport

Is there a way to make the header and footer expand to 100% width while keeping the middle content width variable? You can view the source at http://jsfiddle.net/9dWcZ/ HTML: <div class="header"> this is header </div> <div class="content ...

Issue encountered when sending information to asmx web service via ajax and displaying the result on an HTML page with a javascript function

I have developed an ASMX web service that looks like this: [ScriptService] public class CurrencyData : System.Web.Services.WebService { [WebMethod] public string DisplayCurrency(double amount, string sign ,string style) { swi ...

Transferring HTML5 Video data by breaking it into segments and streaming it through several HTTP/

Looking for ways to speed up the loading time of an html5 video? Is there a method to make a browser process each webm video fragment as individual TCP streams, in order to take advantage of HTTP/2's enhanced parallelization? ...

Unable to click on element in Firefox browser

Encountering an issue with the following error message: Element is not clickable at point (791, 394). Other element would receive the click: Command duration or timeout: 66 milliseconds Any ideas on what's causing this? Using selenium web driver ve ...

Issue with overlapping positioning of child components in React

I've come across multiple inquiries addressing this issue, yet none of them have provided a solution that fits my problem. In my scenario, there's a Parent component containing three Child components. import React, { Component } from 'react ...