Change the font size of the root element (html) dynamically

I’m new to ionic and really loving it.

In my first app I’m trying to add two buttons that will allow the user the change the font size of the whole app. After some reading I discovered that I need to control the font size of the root element (html) as all other child elements are using rem (e.g. relative em) in their font size definition. Even though I can do that statically by setting the SASS variable ($font-size-root), I cannot find a way to do that dynamically.

For those interested in this, here is how to do it statically. Edit src/theme/variables.scss and add at the end of it the following line:

$font-size-root: 66.5%;

The default value is 62.5%.

Dynamically, I can do it for specific elements by adding code similar to:

<ion-content padding text-justify [ngStyle]="{‘font-size’: font_size + ‘%’}">

but in order to do that for the root html element I need to have some access to it first.

Is there any way to do that properly? Btw, I found another similar topic but there wasn’t any specific anwer.

OK, figure it out myself. It’s a two step process.

Step #1: In the page’s template (*.html) add the “increase size” button:

<button (click)=“increaseFontSize()”>

Step #2: In the page’s class (*.ts) add the function definition:

increaseFontSize() {
    this.font_size = this.font_size * 1.1;
    let htmlRoot:HTMLElement = <HTMLElement> document.getElementsByTagName("html")[0];
    if (htmlRoot != null) {
       htmlRoot.style.fontSize = this.font_size + '%';
    }
}
1 Like

Seems like there should be a more angular way to do it that doesn’t require manipulating the DOM manually

have you tried

<ion-content [style.font-size]="fontSize + 'rem'">
    Some Text
    <button (click)="increaseFontSize()">BIGGER</button>
</ion-content>

And in your class

fontSize: number = 1;

increaseFontSize() {
    this.fontSize = this.fontSize * 1.1;
}
1 Like

Thanks for your feedback.

What you are suggesting was my initial thought, but this affects only the text that’s directly under the ion-content section, not headers, buttons or other components. I wanted to change ALL font sizes with a single click, not just a specific element. Btw, the Math.floor should be removed if you are planning to work with rem.

Is there a way of doing the increase in font size only to certain html files and only to the text in the Ion-content?