I would like to offer the user the option to choose the font-size of the whole app on his own. My problem is that I don't know how to change the font-size globally on runtime. I already tried adding a class in global.css:
...
* {
font-size: large; //that works
}
...
.large-font {
font-size: large; //that doesn't work
...
but that didn't work because I also don't know which are the actual HTMLElements, of which the font-size has to be changed.
This is the current version of my function for the (ionChange)-Event:
onSelectFontSize() {
const app = Array.from(
document.querySelectorAll('*') as unknown as HTMLCollectionOf<HTMLElement>
);
console.log('app: ', app);
// eslint-disable-next-line @typescript-eslint/prefer-for-of
for (let i = 0; i < app.length; i ) {
app[i].style.setProperty('font-size', '96px !important');
}
}
I am working with ionic 6 Angular 14 with almost 2 months of experience in these technologies. I have already tried other solutions here in stack overflow.
Thank you in advance
CodePudding user response:
The following is an example for Ionic React (because I use React, not Angular) but the basic principle should be the same.
Ionic 6 makes extensive use of CSS variables. So my solution was to add font size variables to variables.css
:
:root {
/* https://developer.apple.com/design/human-interface-guidelines/ios/visual-design/typography/ */
--app-text-size-base: 1.25rem; /* Assumes 16px base size. */
--app-text-size-title: calc(var(--app-text-size-base) * 1.2); /* 24px */
--app-text-size-title-h1: calc(var(--app-text-size-base) * 1.3); /* 26px */
--app-text-size-title-h2: calc(var(--app-text-size-base) * 1.2); /* 24px */
--app-text-size-title-h3: calc(var(--app-text-size-base) * 1.1); /* 22px */
--app-text-size-title-h5: calc(var(--app-text-size-base) * 0.9); /* 18px */
--app-text-size-title-h6: calc(var(--app-text-size-base) * 0.8); /* 16px */
/* iOS default big size */
--app-text-size-small: calc(var(--app-text-size-base) * 0.85); /* 17px */
--app-text-size-half: calc(var(--app-text-size-base) * 0.5); /* 10px */
--app-text-size-half-negative: calc(var(--app-text-size-half) * -1); /* -10px */
In several places, Ionic assumes a fixed font size, so I had to make various tweaks; see text.scss
in my gist here.
Once this is in place, you can use a simple function to set the CSS variable (React TypeScript example):
const setThemeTextSize = (newTextSize: string): void => {
const root = document.querySelector(':root') as HTMLElement;
if (root) {
root.style.setProperty('--app-text-size-base', `${newTextSize}px`);
}
};