Enlico
Enlico

Reputation: 28416

Confusion about ems in media queries

One source

In Keith J. Grant's CSS in Depth, section 8.2 I read

it's a better idea to use ems in your media queries, based on the browser's default font size (usually 16px).

I'm tempted to understand that ems in media queries are based on the browser's default font size, please correct me if I'm wrong, otherwise the sentence would imply that I am responsible for requesting that the em be based on that font size, and nothing in the sample code suggests anything like that.

Another source

On the other hand, from the specs I read

EXAMPLE 27

[…]

@media (min-width: 20em) { … }

The em value is relative to the initial value of font-size.

and if I click on that link, I'm brought to the definition of the font-size property where I read that it's initial value is medium.

My interpretation

My question

Are the two sources saying the same thing? How do the two definition relate to the rem unit?

Upvotes: 2

Views: 815

Answers (2)

Alohci
Alohci

Reputation: 82986

In normal situations, 1em is a relative unit, and in a font-size it's relative to the font-size of its parent element. medium is an absolute unit. In different browsers it can be set to different pixel sizes, and is chosen to be comfortable to read on a device. A common value for medium is 16px, but other values could be chosen. For example, a user might configure their browser to use a different px value for medium so that they can read the text better.

In media queries, there is no parent element for 1em to be relative to. So it takes the initial value of medium.

So yes, the two sources are saying the same thing, the spec with just a little more precision.

The rem unit plays no part in this. If you use rem in your media query, it will also evaluate to medium. i.e. It would not be affected by any font size assigned to the root element in your styling.

Upvotes: 6

ent3
ent3

Reputation: 192

Maybe this will clarify your understanding:

1em is equal to the current font-size of the element in question. If you haven’t set font size anywhere on the page, then it would be the browser default, which is probably 16px. So by default 1em = 16px.

Source: https://css-tricks.com/css-font-size/

While em is relative to the font size of its direct or nearest parent, rem is only relative to the html (root) font-size.

Source: https://j.eremy.net/confused-about-rem-and-em/

Upvotes: 0

Related Questions