Grow your CSS skills. Land your dream job.

Decimal precision in calculating EM values

  • # April 28, 2013 at 8:14 am

    Hi,

    I wonder if anybody already “researched” how and with which decimal precision browsers calculate EM values?
    The main reason for this is that I use EMs for my media queries,but don’t want them to overlap.

    Opera (Mobile) e.g. seems to need at least a ‘0.05’ higher value to not round it down, while other browsers also do it correctly with a difference of ‘0.001’.
    Even worth behaves the Dolphin HD Browser (Android). Here the minimum difference seems to be ‘0.1’. Given a default font size which equals to 16px this means a “gap” of 1.6 px. So there is slight chance that none of the queries matches (which I would like to avoid).

    Even after some search on Google I wasn’t able to find some helpful informations about how the different browsers calculate and “handle” these values.

    So I will be glad, if someone can enlighten me – thanks!

    Gunther

    # April 28, 2013 at 9:33 am

    I don’t know much on this subject, but with a little research I found this reference on the webkit [LayoutUnit](http://trac.webkit.org/wiki/LayoutUnit) that states they set their browsers to multiples of 1/64th pixel, whereas Mozilla uses 1/60th pixel precision. That page shows how the calculations are rounded.

    # April 30, 2013 at 8:18 am

    Hi Mottie,

    Thanks for the helpful link!
    Actually the problem with EM based media queries without overlapping is one with the roundings of the computed values, which (to make things worse) depend on the value for the basic font size.

    Let me give an example (based on how Opera Mobile does things):
    Assumed the basic font size is equal to 16px and one media query rule is: @media only screen and (max-width: 20em) {…}
    Then it would be the same as: @media only screen and (max-width: 320px) {…}

    So probably the next rule will be something like: @media only screen and (min-width: 321px) and (max-width: …px) {…}
    In our current example the equivalent of one pixel in EM is 1/16em or decimal 0.0625em.

    But assumed a user has set his basic font size up to 24px then our former 1px EM value of 0.0625 is computed as 1.5 (0.0625 * 24).
    And as a browser needs an integer in the end, the value is rounded up to 2px!

    So there is already a one pixel gap which may lead to that no rule matches!

    The other way round there is a similiar problem. But instead of getting a gap it might happen that rules overlap.

    The solution for this problem with EM based media queries would be the support of the calc() syntax, like: @media only screen and (min-width: (20em + 1px)) and (max-width: …30em) {…}

    Unfortunately this is actually not supported by any browser (but would be IMHO most helpful)!

Viewing 3 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic.

*May or may not contain any actual "CSS" or "Tricks".