How to implement responsive font size in rem - boo

2019-07-10 07:59发布

问题:

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.

回答1:

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.



回答2:

If you haven't set the font size anywhere on the page, then it is the browser default, which is probably 16px. So, by default 1rem = 16px, and 2rem = 32px. If you set a font-size of 20px on the body element, then 1rem = 20px and 2rem = 40px.

In addition, em, rem are not an absolute unit - it is a unit that is relative to the currently chosen font size. Unless you have overridden font style by setting your font size with an absolute unit (such as px or pt), this will be affected by the choice of fonts in the user's browser or OS if they have made one, so it does not make sense to use em as a general unit of length except where you specifically want it to scale as the font size scales.

NB: too long for a comment. sorry for that