Home > Net >  How to increase font size relatively when font is pixel based?
How to increase font size relatively when font is pixel based?

Time:08-29

Is there a way to increase the font size of an element by a certain amount when the element css has a font size defined with pixel value?

For example, let's say someone else creates an element with a font size of 10px. I want to increase the font size by 25%.

So if I have an element can I add a class that will increase the font size by 125%? Example:

function increase() {
   //log("test");
   //var container = getElementById("container");
   container.classList.add("adjuster");
}

function decrease() {
  //var container = getElementById("container");
  container.classList.remove("adjuster");
}
.main {
  font-size: 15px;
  margin: 8px;
}

.adjuster {
  font-size: 125%; // increase by 25%
}
<div id="container" >
   Lorem Ipsum
</div>

<button onclick="increase()">
Increase
</button>

<button onclick="decrease()">
Decrease
</button>

Although it looks like it, it's not working. It's that 125% is larger than font-size: 15px.

Basically, is it possible to make a site with increase and decrease font size? BUT where it's not the body container and the font size is pixel based already.

CodePudding user response:

You just must add document before get the html element etc

document.getElementById("container");

You can learn deeply about html dom on https://www.w3schools.com/js/js_htmldom.asp

And you can make variable before the function (globar variable) so you can call that element without declare it every time

const container = document.getElementById("container");
function increase() {
   //log("test");
   container.classList.add("adjuster");
}

function decrease() {
  container.classList.remove("adjuster");
}
.main {
  font-size: 15px;
  margin: 8px;
}

.adjuster {
  font-size: 125%; // increase by 25%
}
<div id="container" >
   Lorem Ipsum
</div>

<button onclick="increase()">
Increase
</button>

<button onclick="decrease()">
Decrease
</button>

CodePudding user response:

Instead of adding a pre defined class with increased fontsize, use window.getComputedStyle to get the current font size, alculate 25% of current value and increase it by that number.

function increase() {
   var container = document.getElementById("container");
   var style= window.getComputedStyle(container , null).getPropertyValue('font-size');
   var fontSize = parseFloat(style);
   container.style.fontSize = (fontSize   (fontsize * 0.25))   'px';
}
  • Related