Adjust the font size automatically to fit within the image container dimensions

How can I make sure that my text and image scale together while maintaining their relative positions on the page? Currently, I am using vw to scale the text, but I'm not able to keep it in sync with the image. My goal is to have the text shrink proportionally with the image so that the ratio between them stays consistent as they both respond to changes in size.

Even after attempting to set the image and container to absolute positioning, I still encounter the same issue.

img {
  position: absolute;
  display: block;
  margin-left: auto;
  margin-right: auto;
  max-height: 900px;
  max-width: 1364px;
  width: 100%;
  height: auto;
  box-shadow: 10px 10px 5px grey;
}

.container {
  position: relative;
  margin-left: auto;
  margin-right: auto;
  color: bisque;
  font-style: italic;
  font-family: Verdana;
  font-size: 0.6vw;
}

.top-left-text {
  position: absolute;
  top: 8px;
  left: 620px;
  text-align: left;
}

.top-middle-text {
  position: absolute;
  top: 8px;
  left: 1140px;
  text-align: left;
}
<div class="container">
  <img alt="lagaremeny" height="703" src="lagaremeny.png" width="1376">
  <div class="top-left-text">

    <div class="auto-style1">

      <strong>Sallader</strong>
    </div>
    <ul>
      <li>Kycklingsallad 69kr</li>
      <li>Amerikansk sallad 69kr</li>
      <li>Grekisk sallad 69kr</li>
      <li>Tonfisk, ägg och rödlök 69kr</li>
      <li>Västkuströra och ägg 74kr</li>
      <li>Skagenröra och ägg 74kr</li>
      <li>Salami och sallads ost 74kr</li>
      <li>Kebabröra 69kr</li>
      <li>Räkor Handskalade Lyxräkor (MFC märkt) 94kr</li>
    </ul>
    Alla våra sallader består av en bas med isbergssallad,<br> ruccola, röd mangold, röda blad, máche, gurka,<br> mix av körsbergstomater och pasta/eller mer<br> grönsallad och paprika.<br> I alla sallader ingår dressing och bröd.
    <br><br>Dressing: Vitlök, Mango curry, Vinaigrette, Curry,<br> Rhodeisland, Blue cheese, Honung o dijong, Mangoraja.
  </div>
  <div class="top-middle-text">
    <div class="auto-style1">
      <strong>Arbetarmackor</strong></div>
    <ul>
      <li>Ägg och biff</li>
      <li>Ägg och bacon</li>
      <li>Ägg och korv</li>
      <li>Ägg, köttbullar och rödbetssallad</li>
      <li>Ägg och sill</li>
      <li>Ägg och västkustsallad</li>
      <li>Leverpastej</li>
      <li>Ost och paprika</li>
      <li>Ost och skinka</li>
      <li>Köttbullar och rödbetssallad</li>
      <li>Rostbiff och potatissallad</li>
    </ul>
    Alla arbetarmackor: 59kr/st.
    <br>Standardtillbehör: sallad, gurka och tomat.
  </div>

My challenge lies in ensuring that when the window is scaled down, the text adjusts its size while remaining fixed in relation to the shrinking image and retaining its original position.

Answer №1

If you're open to using external libraries, you might want to consider experimenting with the jQuery plugin FitText.js.

Alternatively, I've devised a solution that leverages the window's `resize` event listener to dynamically adjust font sizes based on the parent container's width.

To implement this in your HTML file, simply embed the following JavaScript within a script tag:

<script defer>
  setFontSize('container', 14)

  function setFontSize (containerClassName, fontScale) {
    resizeFontInContainer() // initialize the page with scaled font
    window.addEventListener('resize', resizeFontInContainer) // add event listener for window resize

    function resizeFontInContainer () {
      let containers = document.getElementsByClassName(containerClassName)
      for (var i = 0; i < containers.length; i++) {
        let containerWidth = containers[i].offsetWidth
        containers[i].style.fontSize = `${containerWidth * fontScale / 1000}px`
      }
    }
  }
</script>

Note that some CSS tweaks were necessary to tailor this solution to your specific requirements.

If this alignment with what you had envisioned, or if you need further clarification, feel free to provide more details about your expectations.

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

Apply CSS3 attributes in real time

The for loop I have is functioning properly: <div id="page1div"></div> <script> list = " "; for (var i = 0 ; i < length ; i++) { list = "<h1 class='entriesdisplayed'>" + item(i) + ...

Eliminating undesired borders of table cells using CSS

I am facing a unique and puzzling issue. Here is the simple markup: <table> <thead> <tr><th>1</th><th>2</th><th>3</th></tr> </thead> <tbody> <tr>< ...

When hovering over an object in three.js, the cursor should change on mouseover

In my scene, I have added a sphere and plane geometry. Clicking on the plane geometry will open a linked website. Now, when hovering over the plane geometry, I want the mouse cursor to change to a hand pointer icon, and revert back to its original style ...

Creating a new table based on an if statement from an HTML table index value of x

Hey everyone, I could really use your assistance. I've been attempting to create an if statement based on the values in my HTML table's index-x (where x represents the column index). I've successfully managed to convert the table into an arr ...

Tips for incorporating basic code into an android app

I find myself puzzled about the placement of regular Java code in an Android application. Using the Eclipse SDK, when you create an application, it automatically generates a .java file with an OnCreate() method. Should I insert my code within this method? ...

Element with a fixed position within an iScroll container

Has anyone encountered an issue with fixing an element with position: fixed inside a big Iscroll page? It seems like the element scrolls along with the content due to the transition imposed by Iscroll. I'm trying to fix the "FIXTHIS" element, but it ...

"The onkeydown event dynamically not triggering for children elements within a parent element that is contentEditable

Can anyone offer some insights into why this code isn't functioning as expected? My goal is to attach the listener to the children elements instead of the body so that I can later disable specific keystrokes, such as the return key. <!DOCTYPE html ...

Customize the appearance of tables in your WordPress theme

I'm currently working on a website using the Wordpress Twenty Ten theme and I've run into an issue with inserting html tables. The theme seems to be overriding my styling, resulting in very unattractive tables. I've attempted to fix this pro ...

Tips for printing several div elements with a set width and height without altering their size

At my workplace, we have perforated paper that employees fill out and cut to use as information cards. I am working on writing code using ASP.net core to input information onto these cards after a transaction. I have created a preview of the card in an HTM ...

Sliding Toggle: Panel Revealed with Button Slide

Currently, I am working on implementing a jquery slide tab feature. The functionality is working fine on button click. However, I want the button to stick with the panel and slide along with it. At the moment, the button remains fixed while the panel slide ...

5 Bootstrap Form Validation: Improve Your Form Experience

While working with Bootstrap 5 forms, I encountered an interesting issue where I applied the class was-validated to a form. This caused a red border to be displayed around the input field, but as soon as I entered text in the textbox, the red border was ...

Ensuring that the header contains a centered element and a right-justified element, both aligned perfectly vertically

I'm currently working on creating a unique header design for my website, where I want one element to be centered and another element to be right-justified within the header. After brainstorming different approaches, I came up with the following metho ...

The CSS attribute for setting the background color of Shell in css/default.css does not produce any visible

Currently working my way through the book "Eclipse 4 Plug-in Development by Example Beginner's Guide", specifically on the section titled "Time for action – styling the UI with CSS". The guide instructs to edit the "css/default.css" file and add th ...

Enter the variable into the parameter

I'm working with some Javascript code: document.getElementById("Grid").style.gridTemplateRows = "repeat(3, 2fr)"; I'm trying to insert a variable as an argument to modify my CSS style. When I attempt the following: "repe ...

Conceal the second click action within the anchor tag

Is there a way to hide the second click event on all anchor tags except those that trigger popupfun? I have a sample page set up. [Check out the JS Fiddle here][1] http://jsfiddle.net/ananth3087/LgLnpvf4/15/ Link Anchor Tags: The page includes two ...

Is it possible to programmatically hide the Textarea and submit button for each row in a PHP-generated database table?

After spending a considerable amount of time on this project, I'm looking to incorporate a JavaScript effect (hide/unhide) into a basic submit form. Although the functionality is successful, it seems to be limited to only one row in the database tabl ...

"Learn how to position a div element below the header div and above the footer div while maintaining full height in

Recently delving into the world of reactjs, I find myself facing a challenge with a page that contains 3 distinct blocks formed by divs. Have a look at the layout on my page: My Page This is the code snippet I have worked on: return ( <div> ...

Modifying object properties in JavaScript

Looking to update a boolean attribute for an object in JavaScript (in this case, the object is part of fullPage.js library). I am interested in turning off the navigation attribute by setting it to false, and ideally would like to do this from a separate f ...

How can I eliminate the gap above the footer in iframes alignment?

I have a setup with four iframes: header, menuframe, bodyframe, and footer. The menuframe and bodyframe are positioned next to each other with space between the footer and the menuframe/bodyframe. How can I remove this space? Here is the CSS: iframe{ ...

The $_GET variable disappears once the form is submitted

Here's the issue I'm facing: On my homepage, there are tables with rows generated from the database using while loops. Each row includes a cell where an event can be added to that specific row. To achieve this, I pass the row ID as a $_GET variab ...