Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement responsive font size in rem - bootstrap

I am using bootstrap 3 in my project and I see that there are 2 declarations of font-size in bootstrap as below:

Scaffolding.less

html { font-size:10px;}

body{ font-size : @font-base-size; }

And the @font-base-size is defined as 14px in variables.less

I have been reading stuff where one way of having responsive font size was to have base font size as px defined in body or html as then use font sizes in rem for different components in body such as p, h1 etc.

But I am not sure, where do I define the base font, should it be in html OR body?

And why does bootstrap has different font size in html and body?

My observations: When I define some font size in px in html, then only rem thing works for everything, defining font size as px in body doesn't work with rem.

like image 322
whyAto8 Avatar asked Aug 31 '25 18:08

whyAto8


1 Answers

The rem unit is relative to the root, or the html element. Thus defining the base font size should happen on the html element.

Defining a font-size on the body will work, but all child elements which have a font-size definition using rem units will fall back to the root/html element to calculate their absolute size.

So:

html {
  font-size: 10px;
}

body {
  font-size: 15px;
}

.parent {
  /* font-size will be 15px here */
}

.parent .child {
  font-size: 1.2rem; /* resolved to 12px */
}

As to why Bootstrap uses 2 font-sizes: the 10px font-size on the html element is just part of some global reset they use. Also, some margins/paddings are calculated using the base font size, so it's best not to interfere with that too much.

like image 188
Gerrit Bertier Avatar answered Sep 02 '25 09:09

Gerrit Bertier