Change the size of text automatically in a div while ensuring it is responsive

I am looking to merge two functional JSFiddle projects and have them work in conjunction with each other.

JSFiddle-1 : http://jsfiddle.net/MYSVL/3050/

window.onresize=function() {
    var child = $('.artist');
    var parent = child.parent();

    child.css('font-size', '18px');

    while( child.height() > parent.height() ) {
        child.css('font-size', (parseInt(child.css('font-size')) - 1) + "px");
    }

The content within the artist container in this project is responsive, adjusting to the maximum font size when the screen is larger, and minimizing to smallest font size on a smaller screen.

JSFiddle-2 : http://jsfiddle.net/MYSVL/3047/

function calcDivHeights() {

     window.onresize=$(".artist").each(function () {

        var child = $(this);
        var parent = child.parent();

        //child.css('font-size', '18px');
        while (child.height() > parent.height()) {
            child.css('font-size', (parseInt(child.css('font-size')) - 1) + "px");
        }

    });
}

In this second project, the function is examining every artist div and readjusting the font size based on the while condition. However, I am facing difficulties in making it responsive like my JSFiddle-1. Once the text size decreases, it remains small even if I enlarge the screen. I aim for JSFiddle-2 to operate exactly like JSFiddle-1, ensuring that the text responsive adapts to the screen size.

If anyone can assist me or modify my JSFiddle-2 to achieve this objective, I would greatly appreciate it.

Thank you in advance.

Answer №1

It appears that there are no notable differences between the two fiddles you've provided, with the exception of the commented code child.css('font-size', '18px'). Both should function in a similar manner.

The second fiddle seems to encounter issues when the window is resized to a smaller resolution, causing the height of child to be equal or smaller than that of parent. Subsequently, upon returning to a larger resolution and running

while( child.height() > parent.height() )
, the condition fails as the child's height is no longer greater than the parent's.

To address this issue, consider implementing the following solution:

$(document).ready(function () {

function adjustFontSize() {
    var child = $('.artist');
    var parentHeight = child.parent().height();
    while( child.height() > parentHeight ) {
        child.css('font-size', (parseInt(child.css('font-size')) - 1) + "px");
    }
    while( child.height() < parentHeight ) {
        child.css('font-size', (parseInt(child.css('font-size')) + 1) + "px");
    }
};

adjustFontSize(); // Executed on document ready
window.onresize = adjustFontSize; // Triggered on window resize

});
.artist-container {
    width: 20%;
    height: 40px;
    border: 1px solid black;
    overflow: hidden;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="artist-container">
    <div class="artist">Audhit Audhit Audhit Audhit Audhit Audhit Audhit</div>
</div><br>
<div class="artist-container">
    <div class="artist">Lorem</div>
</div><br>

Answer №2

CSS media queries are a game-changer when it comes to creating responsive web designs. Instead of relying solely on Javascript for all calculations, using media queries can streamline the process.

When designing for responsiveness, it's helpful to consider three main sizes:

  • Phone (approximately 400px width)
  • Tablet (around 800px width)
  • Computer (greater than 800px width)

One effective way to implement this is by adopting a "desktop-first" approach:

/* DESKTOP */
body {
  font-size: 1em;
  ...
}
...
/* General rules for desktop
...

/* TABLET */
@media screen and (max-width: 800px) and (min-width: 400px) {
   /* Adjust specific rules here */
   body {
      font-size: .75em;
   }
   ...
}

/* PHONE */
@media screen and (max-width: 400px) {
   /* Modify styles accordingly */
   body {
      font-size: .75em;
   }
   #div1 {
      height: 20%;
   }
   ...
}

Additionally, utilizing relative units like em, vw, vh, rem, and percentages can enhance flexibility in your design.

For further insights on responsive web design, check out this informative resource.

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 the explode function to parse an XML file and extract the data into a unified array output

My XML file can be found here. I am currently parsing it using the following code: <?php $xml=simplexml_load_file('info.xml'); foreach($xml->testcase as $var){ $var=explode('/',$var->script); $module =array($var[2]) ...

Initiating a AJAX upload upon selection of a specific option from a select menu

Recently, I have been exploring ways to enhance my layout page by implementing an option for users to upload new logos on the spot. Currently, users are able to choose their desired image through a drop-down selection feature. I am interested in adding a f ...

Detecting the Presence of 5 Consecutive Numbers in an Array using JavaScript

I am struggling to find a way to identify if a sorted Array consists of 5 numbers in consecutive order. The catch here is that the Array can have duplicate and double-digit numbers mixed within it. I attempted to implement this logic but unfortunately, my ...

Is it possible to customize the background color of select2 boxes separately for each option?

I recently implemented the select2 plugin and now I'm looking to add a new class within the .select2-results .select2-highlighted class in order to change the background color. Does anyone have any suggestions on how to achieve this? ...

The alignment of the ml-auto class is not properly positioning the navbar links to the right

I've been using the reactstrap library and following this guide: In the example provided, the <nav className='ml-auto' navbar> is pushing the <NavItem> to the right. However, in my implementation (which is very similar to the ex ...

I'm having trouble sending my data correctly using Ajax with the JSON data type

Within my code, I have successfully implemented an ajax request which triggers a function named 'reorder_rows' and outputs 'function reached!'. var data = {}; data['reorder_rows'] = 'test'; data['token'] = ...

selenium cannot detect the button's visibility even though it has been fully loaded

My goal is to automate the process of searching for 'easy apply' jobs on LinkedIn. However, I am encountering an error message saying "could not be scrolled into view" when attempting to click the 'Apply' button for 'easy apply&ap ...

Obtaining Serialized Data

Using the JavaScript serializer to send data to JavaScript: var jsSerializer = new JavaScriptSerializer(); var result = (from c in dt.AsEnumerable() select new { Latitude = c.F ...

Interacting with Django backend via AJAX to trigger Python functions using jQuery/AJAX

Currently, I am developing a small website using Django. Within this project, there are DateTime fields that need to be handled. My intention is to utilize ajax by implementing another button to establish the UTC date while taking into consideration sola ...

Preventing Vue.js SPA from accessing cached version when JWT expires: the solution

I'm encountering an issue with my Vue.js / Express application that I can't seem to resolve. Here's how the process unfolds: An unauthenticated user logs into the app and is presented with the login page. Once successfully authenticated, t ...

Is there a way to use CSS to swap out the content of one HTML element with another HTML element's content?

Having an issue with editing or locating a plugin's HTML template on WordPress. Wondering if it is possible to replace the content of one HTML element with another using just CSS? Appreciate any help! ...

Regular expressions tailored for a precise format in JavaScript

Is it possible to create a regex that can validate a specific format? For example, if I have version numbers like v1.0 or v2.0 v1.0 or v2.0 My current regex expression only validates the existence of v, a number, or a .. How can I implement validation ...

Mastering the art of looping through an array efficiently in jQuery using AJAX without unnecessary repetition

I have a jQuery function that extracts values from the wp_localize_script declaration. <script type='text/javascript'> /* <![CDATA[ */ var assjs = {"action":"get_ass_counts","path":"http:\/\/localhost\/wordpress-dev\ ...

"Maximizing Efficiency: Chaining Several Actions Using the JavaScript Ternary Operator

When the condition is true, how can I chain two operations together? a = 96 c = 0 a > 50 ? c += 1 && console.log('passed') : console.log('try more') I attempted chaining with && and it successfully worked in react, b ...

When the form is submitted, the value is not refreshed if the button is exited

I need to have a form where the save button is positioned outside of the form elements. However, when I move it elsewhere, the form does not refresh. <form ng-submit="save()" action="" name="addInv" novalidate> <div class="col-md-10 ...

"Every time a sanity check is performed, an empty array is returned

I currently have two posts published. Both my localhost and domain name are listed in Sanity's CORS settings, but I am consistently encountering an issue where Sanity returns an empty array. Below is the configuration of my Sanity Client: export ...

Review Limited Screen Size for a Smartphone Website

I have been working on optimizing a mobile website and I utilized CSS to adjust the layout design for screen widths between 150px and 480px. However, during testing on an actual phone, the desktop layout is appearing instead of the custom layout set with C ...

I am facing issues with utilizing if endif for my Internet Explorer stylesheet in HTML/CSS

<!--[if IE]> <link rel="stylesheet" type="text/css" href="ie.css" /> <![endif]--> <link rel="StyleSheet" href="style.css" /> Whenever I apply this code, the content in Internet Explorer is being influenced by both style.css and ie. ...

Tips for creating a function to assign a CSS width using a JavaScript variable?

Here is the code snippet I have been working on: ...<script> function adjustElementSize() { var newSize = window.innerWidth - 600; document.getElementById("spin").style.width = newSize + "px"; document.getElementById("spin").style.height = newSize + ...

Retrieve the data in the format of [1,2,3] from a MySQL database by employing PHP and jQuery

I'm currently working on a jQuery code that connects to getdata.php. The val in this code is a dynamic value and the function gets called every time an option is selected from a dropdown. function getMoleculeData(val){ var molval=val; ...