I'm trying to work out how to use EM media queries in my latest project. However after some testing I've found that the media queries are ever so slightly off and I can't work out why. It might have something to do with it using the parents font size instead of the body. My body is set to 14px
and my workings out look like:
$break-small: 22.8571em; //320px
$break-smallish: 40em; //560px
$break-med: 54.8571em; //768px
$break-medish: 68.5714em; //960px
$break-desk: 73.1428em; //1024px
body font size:
body{
font-size: 14px;
line-height: 1.5;
min-height: 100%;
}
*(from my SCSS breakpoint variables) From what I understand I did: 768 / 14 (base font size) = width in em's
Say I've a div
called header, there is no font-size
set on this div
, only children of this div
. Surely it would still then use the body font-size
?
Please try this code. I have already used this my last project it working in fine. so please try.
Your guesswork is correct, the
em
unit sets the font size relative to the parent element's font-size, not relative to the document root. If you're looking for the latter you're looking for therem
unit, but browser support might be a problem for you, depending on your application.See the following Fiddle for a sample: http://jsfiddle.net/afp46/
HTML:
CSS:
I would highly recommend you do font-sizing with
rem
, which stands for "root em". It's much more consistent. Read more about it here: http://snook.ca/archives/html_and_css/font-size-with-remAlso, I would recommend adding this to your CSS:
Now, your rems or ems will be easy to convert. 10px font-size would be 1rem or 1em. Nice, right? :) Again, use rems, its a much better practice these days.
Ems in media queries are never based on the font size of
body
, or any other element for that matter. They always refer to the default font size set by the user in the browser preferences. In most browsers this default font size is around 16px, and in CSS this corresponds to the initial value of thefont-size
property which ismedium
. From the spec:This same default font size is inherited by the root element, which is
html
, notbody
(see here). Specifying a relative font size onbody
just meansbody
bases its own calculation on the computed font size ofhtml
. This being stated, note that settingfont-size
onhtml
will not affect how ems are calculated in media queries either.I would change that to body font size 100% and then you have the flexibility of EMs and %s site wide