Is there a way for me to adjust the font size across the entire page?

Most CSS classes come with a fixed font-size value already set. For instance:

font-size: 16px
font-size: 14px
etc.

Is there a way to increase the font size of the entire page by 110%? For example, font-size: 16px -> 17.6 font-size: 14px -> 15.4

Answer №1

There is no simple solution for this issue.

The sizes are hardcoded and must be adjusted manually.

A recommended approach would involve updating the CSS to use relative sizes, likely utilizing the rem unit, allowing for font scaling throughout the entire document by setting the html element's font size.

The optimal method would entail editing the original stylesheet.

An alternative method would involve using JavaScript to iterate through existing rulesets, identifying and modifying font-size properties as needed.

for (const sheet of document.styleSheets) {
  for (const rule of sheet.cssRules) {
    if (rule.type === CSSRule.STYLE_RULE) {
      // Support for recursing into other rule types, like media queries, left as an exercise for the reader
      const {
        fontSize
      } = rule.style;
      const [all, number, unit] = fontSize.match(/^([\d.]+)(\D+)$/) || [];
      if (unit === "px") {
        // Other units left as an exercise to the reader
        rule.style.fontSize = `${Math.round(number / 16)}rem`
      }
    }
  }
}
html {
  font-size: 1.4em;
}

p {
  font-size: 20px;
}

p span {
  font: 12px "Fira Sans", sans-serif;
}

x {
  /* No font rules at all */
  background: green;
}
<p>Hello <span>world</span></p>

I highly recommend correcting this issue in the source code rather than using a workaround in the browser.

Answer №2

One way to modify styles in a more efficient manner is by navigating the Document Object Model (DOM) structure instead of altering each individual style rule. This method can be particularly beneficial for documents containing numerous styles and a compact DOM.

Simplified approach:

function adjustTextSize(element){
    var currentSize = window.getComputedStyle(element, null).getPropertyValue('font-size');
    if (currentSize) {    
        currentSize = parseFloat(currentSize.replace("px",""));
        element.style.fontSize = (currentSize * 1.2) + "px";
        for(var i=0; i < element.children.length; i++){
            adjustTextSize(element.children[i]);
        }
    }
}
adjustTextSize(document.body);

This methodology preserves the original font size to allow for adjustments at various sizes. It could potentially be linked to a user preference setting.

const ratio = 1.2;
function adjustTextSize(element){
    var originalSize = element.getAttribute("data-orgFontSize");
    const currentSize = window.getComputedStyle(element, null).getPropertyValue('font-size');
    if (!originalSize) {
        originalSize = currentSize;
        element.setAttribute("data-orgFontSize", currentSize);
    }

    if (originalSize) {    
        const size = parseFloat(originalSize.replace("px","");
        element.style.fontSize = (size * ratio)  + "px";
        for(var i=0; i < element.children.length; i++){
            adjustTextSize(element.children[i]);
        }
    }
}
adjustTextSize(document.body);

Answer №3

Would it work to have a separate CSS file specifically for font sizes, and then place it at the end of the line so that it takes precedence over the default font sizes?

Answer №4

Fork the code from @Quentin and attempt to adjust the font-size of all elements by the same ratio.

for (const sheet of document.styleSheets) {
  for (const rule of sheet.cssRules) {
    if (rule.type === CSSRule.STYLE_RULE) {
      // Support for recursing into other rule types, like media queries, left as an exercise for the reader
      const { fontSize } = rule.style;
      const [all, number, unit] = fontSize.match(/^([\d.]+)(\D+)$/) || [];
      if (unit === "px") {
        // Other units left as an exercise to the reader
        rule.style.fontSize = `${number / 16}rem`
      }
    }
  }
}

function font_size_set(new_size){
  document.documentElement.style=`font-size: ${new_size}px`;
}
html {
  font-size: 1em;
}

p {
  font-size: 20px;
}

p span {
  font: 12px "Fira Sans", sans-serif;
}

x {
  /* No font rules at all */
  background: green;
}
<select onchange='font_size_set(this.value*16)' style="float:right">
  <option value=1>100%</option>
  <option value=1.5>150%</option>
  <option value=2>200%</option>
  <option value=3>300%</option>
</select>

<p>Hello <span>world</span></p>

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

Interactive Sidebar Navigation Content

On my website, I have a navigation sidebar that contains links to all of the main site pages. Each page has the same links, except the link to the current page is not included, making it easy to visually identify which page you are on. Currently, I manuall ...

What is the best way to modify just a portion of the state in React?

Consider the following State object: const initialState = { data: { user: '', token: '', } } In the Reducer function: case 'DO_SOMETHING': return {...state, data: action.payload } If I make a shallow copy of th ...

Executing ESM-Enabled Script in Forever

Is it possible to execute a script using the option -r esm in Forever? When I try to run the configuration below, I encounter an error message that reads: Unexpected token import. Here is the configuration: { "uid": "app", "script": "index.js", "s ...

Enhancing SVG graphics dynamically with JavaScript and ensuring compatibility across different web browsers

I am currently working on incorporating an element into an existing SVG file. Interestingly, the process runs smoothly on Chrome and Firefox but encounters issues on Edge. I aim for it to function seamlessly on the latest versions of all three browsers, wi ...

Learn how to trigger an HTTP exception after a failed command in a saga with NestJS CQRS

Currently utilizing the NestJS CQRS pattern to handle interactions between User and UserProfile entities within my system. The setup consists of an API Gateway NestJS server along with dedicated NestJS servers for each microservice (User, UserProfile, etc. ...

Tips for adjusting the div style when resizing the browser

As I work on a script, I encounter an issue where the style of a div should change when it becomes larger due to resizing. Even though I have come up with a solution for this problem, there are still some inconsistencies. Sometimes the width is reported a ...

Phonegap app unable to process AJAX post request, functions properly in browser

My AJAX request is encountering issues specifically when tested on the Phonegap App using iOS10. The code I am working with is as follows and functions perfectly in a browser: if($.trim(firstname).length > 0 & $.trim(email).length > 0 & $.t ...

How can I retrieve the Azure subscription IDs of the currently logged in user using @azure/msal-angular?

I successfully authenticated a user using @azure/msal-angular and received the id_Token, access_Token and tenant Id. Now I am looking to retrieve the logged in user's azure subscriptions. Is there a way to achieve this through msal or are there any Ja ...

Storing data from a form by utilizing AJAX with PHP

Is there a way to save the form data either in a file or a local database using AJAX, while still sending the data through the form action to an external database? If you want to view the source code for my form, you can find it here: http://jsbin.com/ojU ...

Understanding MUI5 prop handling

Recently, I decided to experiment with Material UI 5 sx props just for fun. I encountered a bit of confusion while trying to replicate the behavior of the previous MUI 4 makeStyles function. Specifically, I was attempting to pass JSS classnames to sx props ...

Creating a customizable navigation bar using only CSS

I'm currently working on creating a navigation bar using only HTML and CSS, without the need for JavaScript to open and close it. However, I've encountered an issue where the navigation bar remains open even after setting display: none or visibi ...

Is there a way to modify the text color within the thumb-label of the Vuetify v-slider component?

Lately, I've been facing some challenges and my objective is to change the color of the thumb label on my v-slider to a custom one that is defined in the component's design. Can anyone provide guidance on how to achieve this? Regards, Joost ...

What steps should I take to ensure that Vim properly formats the indentation for this JavaScript code?

Currently an Emacs user, but trying out Vim for a change. :) I'm really enjoying the quick keystrokes and the overall philosophy of Vim, however I've been running into some issues with the more advanced features. One problem I'm having is w ...

Executing the serverless invoke local command produces no output

Attempting to locally run a node lambda for debugging purposes. Utilizing Serverless and the provided launch configuration in vsCode. { "version": "0.2.0", "configurations": [ { "type": "node", "request": "launch", "name": "Launc ...

Exploring the world of unit testing for Sails JS 1.0 helper functions

Currently, I am in the process of setting up unit testing for my SailsJS 1.0 application. My goal is to simulate the DB without needing to execute 'sails lift' to run tests. In my application, there is a straightforward actions2 (node machine) h ...

JavaScript can be utilized to generate an array containing duplicated phrases from a given text

Here's a simple concept: you enter text in a textarea, click "send," and receive a list of recurring phrases. When I say phrases, I mean sequences of two or more words that repeat. While I can identify single words, detecting these phrases is where I& ...

How can I align my logo on the website header separately from the menu tabs while keeping them on the same row?

Trying to vertically align a logo and headers' tabs in the same row can be quite challenging, especially when the logo is taller than the tabs. I've attempted different methods, including using padding to manually adjust the alignment, but it&apo ...

Failure to trigger a follow-up function in webSQL transaction's success callback

Review the code below. I have called setQuestion() within the successCallBack of db.transaction but am encountering an error: Uncaught TypeError: this.setQuestions is not a function. Can you spot any issues in my code? game.module( "game.scenes.scene" ) ...

Setting the state of a nested array within an array of objects in React

this is the current state of my app this.state = { notifications: [{ from: { id: someid, name: somename }, message: [somemessage] }, {..}, {..}, ] } If a n ...

Issue with font-size changes using css variables in Angular not updating in browser for specific fields

Utilizing CSS variables, I have implemented a feature that allows users to adjust the font size to small, medium, or large. While this functionality works correctly for most fields, there are certain instances where the value is applied but not displayed. ...