Adjust font size based on screen dimensions

I am working on optimizing font sizes for different screen sizes in HTML elements. Currently, I use a script to dynamically adjust the font sizes based on window width, but it is making my code messy:

<script>
$(window).resize(function(){
$('#first').css('font-size',($(window).width()*0.2)+'px');
$('h2').css('font-size',($(window).width()*0.02)+'px');
$('h1').css('font-size',($(window).width()*0.03)+'px');

This method works for a few elements, but I have many more to consider. As someone still learning HTML/CSS/JavaScript, I'm looking for suggestions on a better approach.

If you have any ideas on how to improve this process, I would greatly appreciate your input!

Answer №1

Utilizing the latest CSS units, vw and vh (viewport width/height), can address this design concern.

For detailed insights, refer to an insightful article on css-tricks illustrating the application of these units for typography.

Below is an example extracted from the article:

h1 {
  font-size: 5.9vw;
}
h2 {
  font-size: 3.0vh;
}
p {
  font-size: 2vmin;
}

Thus, h1 will exhibit a font size equivalent to 5.9% of the viewport width, etc.


Nonetheless, employing viewport units exclusively for font-size might lead to issues whereby under extremely narrow viewports, the text size could become too small or vice versa.

To tackle this challenge effectively, adopting a method like Fluid Type also known as CSS Locks can be advantageous.

A CSS lock involves defining:

  • a minimum value and a maximum value,
  • two breakpoints (typically based on viewport width),
  • and between those breakpoints, the actual value linearly transitions from the minimum to the maximum.

(Refer to this article on CSS locks explaining the intricate math behind it in detail.)

Suppose we want to implement the above technique with a scenario where the minimal font size equals 16px at a viewport width of 600px or less, gradually increasing until reaching a maximum of 32px at a viewport width of 1200px.

We can utilize this SASS mixin which handles all the equations, making the CSS appear as follows:

div {
  /* Gradually increase font-size from 16->32px 
     within a viewport range of 600px-> 1200px  */
  @include fluid-type(font-size, 600px, 1200px, 16px, 32px);
}
@media screen and (max-width: 600px) {
  div {
     font-size: 16px;
  }
}
@media screen and (min-width: 1200px) {
  div {
     font-size: 36px;
  }
}

// ----
// libsass (v3.3.6)
// ----

// =========================================================================
//
//  PRECISE CONTROL OVER RESPONSIVE TYPOGRAPHY FOR SASS
//  ---------------------------------------------------
//  Indrek Paas @indrekpaas
//
//  Inspired by Mike Riethmuller's Precise control over responsive typography
//  http://madebymike.com.au/writing/precise-control-responsive-typography/
//
//  `strip-unit()` function by Hugo Giraudel
//  
//  11.08.2016 Remove redundant `&` self-reference
//  31.03.2016 Remove redundant parenthesis from output
//  02.10.2015 Add support for multiple properties
//  24.04.2015 Initial release
//
// =========================================================================

@function strip-unit($value) {
  @return $value / ($value * 0 + 1);
}

@mixin fluid-type($properties, $min-vw, $max-vw, $min-value, $max-value) {
  @each $property in $properties {
    #{$property}: $min-value;
  }

  @media screen and (min-width: $min-vw) {
    @each $property in $properties {
      #{$property}: calc(#{$min-value} + #{strip-unit($max-value - $min-value)} * (100vw - #{$min-vw}) / #{strip-unit($max-vw - $min-vw)});
    }
  }

  @media screen and (min-width: $max-vw) {
    @each $property in $properties {
      #{$property}: $max-value;
    }
  }
}

// Usage:
// ======

// /* Single property */
// html {
//   @include fluid-type(font-size, 320px, 1366px, 14px, 18px);
// }

// /* Multiple properties with same values */
// h1 {
//   @include fluid-type(padding-bottom padding-top, 20em, 70em, 2em, 4em);
// }

////////////////////////////////////////////////////////////////////////////

div {
  @include fluid-type(font-size, 600px, 1200px, 16px, 32px);
}
@media screen and (max-width: 600px) {
  div {
     font-size: 16px;
  }
}
@media screen and (min-width: 1200px) {
  div {
     font-size: 36px;
  }
}
<div>Responsive Typography technique known as Fluid Type or CSS Locks. 
  Resize the browser window to see the effect.
</div>

Check out the Codepen Demo here


For Deeper Understanding

Enhance knowledge about precise control over responsive typography

Learn more about Fluid Responsive Typography With CSS Poly Fluid Sizing

Insights into non-linear interpolation in CSS

Answer №2

Utilize media queries to adjust font sizes in your CSS stylesheet

@media(max-width:767px) {
    body {
        font-size: 10px;
    };
}

@media(min-width:768px) {
    body {
        font-size: 11px;
    };
}

@media(min-width:992px) {
    body {
        font-size: 12px;
    };
}

@media(min-width:1200px) {
    body {
        font-size: 13px;
    };
}

Answer №3

Forget about using JavaScript to adjust font sizes...instead, set your font sizes in em units within your CSS files as shown below.

div{
   font-size:2em;
}

Answer №4

Avoid relying on javascript to set font sizes - CSS provides more appropriate methods for that purpose.

Consider using 'em' or '%' along with the font size property to adjust the size of text relative to the dimensions of your webpage and devices.

For example:

font-size: 3em;
font-size: 10%;

Either option will work effectively.

Answer №5

If you're looking to use JavaScript for resizing text dynamically, consider giving this a try:

Answer №6

When using percentages or em units, browsers will adjust font sizes accordingly.

Answer №7

To achieve this, utilize a css media query.

Within the media query, adjust the body size using percentages.

For example: css

@media screen and (max-width: 768px) {
   body {
      font-size: 80%;
   }
}

@media screen and (max-width: 1280px) {
   body {
      font-size: 110%;
   }
}

Next, specify font sizes for each element that needs to resize its font based on browser size or resolution, in percentages.

For instance, if you wish to resize fonts for h1:

h1 {
   font-size: 120%;
}

This approach will give you the desired result.

Answer №8

Instead of relying on pixels for sizing, consider using em units as they will adjust proportionally.

According to a source on Wikipedia:

The use of the em measurement for online content has become more prevalent in web design with the implementation of Cascading Style Sheets (CSS). The World Wide Web Consortium (W3C) now recommends utilizing relative units of measurement like the em over fixed ones such as pixels ("px") or points for creating scalable webpage layouts.

Answer №9

Using JavaScript to dynamically adjust font sizes is generally not recommended. It's better to stick with traditional CSS for this task. You have multiple units such as px, em, %, and rem at your disposal in CSS to size fonts.

If you want your fonts to scale based on screen size, consider using rem units. Alternatively, utilize media queries to specify different font sizes for various screen resolutions. Below are a few example media queries to demonstrate this:

@media screen and (max-width: 1024px) {
    #first { font-size: 204px; }
    h2 { font-size: 20px; }
    h1 { font-size: 30px; }
}

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

Extracting Json data with Jquery

My JSON data format is as follows - I've been struggling to find a way to retrieve the photo reference value. Can anyone help me with this? { "debug_info" : [], "html_attributions" : [ "Listings by \u003ca href=\"http://www.yellowpages. ...

Refreshing the page while using React with fetch results in an undefined return value

After successfully retrieving information from the API and displaying it in a scroll list, an error message appears upon page refresh when inspecting: "Uncaught TypeError: response is null". How can this issue be resolved? The API being used i ...

What is the method for setting up vertical tabs?

Is it possible for someone to provide guidance on how to create vertical tabs for the HTML content below? When a tab, such as tab1 in the left column, is clicked, only the content of tab1 should be displayed in the middle column. The same applies for tab2 ...

Finding an element on a webpage by its innerHTML

Currently, I am tackling a project that involves customers sending inner HTML in an Excel file for me to verify its visibility on a webpage. My current method is to paste the HTML into the Chrome developer console and manually check if the element is prese ...

Challenge encountered when utilizing a value in JQuery/JavaScript

I have successfully implemented a PHP populated table from MySQL and integrated JQuery to monitor button clicks. When a button is clicked, it should retrieve notes related to the clicked name and display them in a JQuery UI dialog window. Everything seems ...

Validation in Antd's dynamic form remains functional even after rows have been deleted

After going through the Antd documentation, I attempted to implement this code snippet from antd dynamic form item: import { Form, Input, Button, Space } from 'antd'; import { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons' ...

Codeigniter experiencing issues with loading CSS file

Currently, I am utilizing codeigniter for a specific project of mine. However, I have encountered an issue related to CSS. The problem seems to be with the loading of CSS files as I keep receiving a 404 error when trying to load them. Surprisingly, all oth ...

What causes my NextJS code to execute multiple times and how can I prevent this from happening?

Struggling to integrate my frontend and backend for a webapp, I encountered an issue where multiple entries are created in the database when a user registers. Upon inspecting with console.log, it appears that my NextJS code is being executed repeatedly. I ...

Display/Conceal content with JQuery on a PHP webpage

I am having trouble with the following code. My intention is to show/hide the content between the #info id when clicking buttons, but nothing seems to be happening. Could you help me identify the issue? echo '<script> $( "#show' . $r ...

Incorporate Javascript to dynamically deactivate a field within an HTML form based on the selected option from a dropdown menu

I'm completely new to JavaScript and have been trying to figure this out on my own by researching online, but unfortunately, I haven't had any luck. I'm currently working on creating a form using HTML and JavaScript. One specific issue I&ap ...

What is the best way to nest components within each other in reactjs?

Is there a way to import another component into this current component without creating a separate file? If so, how can I achieve this using babel and webpack? Specifically, I am looking to create a separate input component with its own state that can be ...

Creating a specialized Adobe DTM Page Load Rule that will exclusively trigger within an iFrame

Within my webpage, there is an iFrame containing specific steps to follow. I am seeking a way to trigger a page load rule exclusively for the content within the iFrame on the page. The URLs of my main webpage and the iFrame are distinct. Both locations h ...

What is the best way to retrieve the current directory of the executed javascript file?

My javascript file is located in a folder at this path: /httpdocs/wp-content/themes/themeName/users/js I have some PHP files in another directory within the same theme, where I need to send Ajax Requests: /httpdocs/wp-content/themes/themeName/users Is ...

Extract the element when the mouse is clicked

I'm currently working on developing a Chrome extension with a specific goal in mind: My aim is to capture the username when a user Ctrl-clicks on a username while browsing Reddit, and then transfer that username from the content script page to the ba ...

Obtaining Inner Table Information within a Parent Table through selenium and C#

I am trying to retrieve the count of elements in the outer table using HTML. Here is the code snippet I have been working on: var reports = driver.FindElements(By.Id("Outer Table")); var formss = new List<object>(); foreach(var item in reports) { ...

Node.js and Express throwing errors when trying to access a certain endpoint with HTTPS and passing parameters

I am experiencing issues with my node.js express webserver that operates on both HTTP and HTTPS, specifically related to express's route parameters and HTTPS. Express allows for parameters in the routing, such as: app.get('/users/:userid', ...

Forward depending on the beginning of the song and the present moment

Is there a way to create a redirect script that will automatically redirect users after a music track has finished playing? I have the total song duration in milliseconds stored in my MySQL table, along with the start time of the track (in central time). ...

Beginner experiencing website overflow problem

After completing a basic web development course, I decided to create my first homepage. While I am satisfied with how it looks on a PC or laptop, the layout gets messy on mobile devices. I tried using <meta name="viewport" content="width= ...

Is there a way to verify if td:nth-child(3) meets or surpasses a certain percentage threshold?

Currently in the process of developing a web page that retrieves various data sets, including three separate tables. My goal is to examine whether the value within the 3rd td element in each TR is equal to or exceeds a certain percentage. How can I determ ...

It appears that using Jquery's .on function in combination with AJAX is not functioning as expected

What is the reason why this code snippet below doesn't work as intended? $(function() { $('#settings').on('click', '.link', function(e) { e.preventDefault(); alert('okay'); }); }); ...