3

I want to allow the user to change the font-size of the entire webpage.

I have set the font-size in rem and I am trying to change the font-size of the root so that it reflects for all the elements.

My markup-

<body >

        <div id="test-text">
        ALL TEXT
        </div>
        <p>sample text</p>
        <p>sample text2</p>
        <span>sample text3</span>
        <h1>tst4</h1>
        <label>label</label>
<button id="inc">inc</button>
</body>

CODE-

$('#inc').click(function(){
    $('body').css('font-size','4rem !important');
})

CSS-

 p{
    font-size: 2rem;
  }

  span{
    font-size: 0.5rem;
  }

The code is not reflecting anything. What am I missing here?

codeBug 07
  • 73
  • 7
  • 1
    You could, possibly, instead change the css class definition: https://stackoverflow.com/a/5891638/2181514 – freedomn-m Oct 13 '20 at 17:08
  • 1
    @freedomn-m Sadly, I cannot use a different stylesheet. – codeBug 07 Oct 13 '20 at 17:20
  • 1
    Consider setting font sizes in `rem` units, rather than `px`. Then all you'd need to do is change the `font-size` of the `html` element and all other font sizes would be relative to that. – Heretic Monkey Oct 13 '20 at 18:07
  • @HereticMonkey Hi. I tried this but for some reason it is not working. I have updated the question. Can you please tell me what am I missing ? – codeBug 07 Oct 14 '20 at 03:57
  • Unrelated, but you have an extra ``. – kmoser Oct 14 '20 at 04:07
  • Note that I said to change the font size of `html`, not `body`. You can also use `px` sizing on `HTML`, since everything will be relative to that (i.e., 2rem will be 32px, 0.5rem will be 8px, etc.). – Heretic Monkey Oct 14 '20 at 12:03

1 Answers1

3

jQuery doesn't always recognize !important. Remove !important and it should work.

How to apply !important using .css()?

$('#inc').click(function(){
    $('body').css('font-size','4rem');
})
p{
    font-size: 2rem;
}

span{
    font-size: 0.5rem;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="test-text">
    ALL TEXT
</div>
<p>sample text</p>
<p>sample text2</p>
<span>sample text3</span>
<h1>tst4</h1>
<label>label</label>

<button id="inc">inc</button>
freedomn-m
  • 27,664
  • 8
  • 35
  • 57
kmoser
  • 8,780
  • 3
  • 24
  • 40