0

I'm working on a website and I'm trying to make every measurement to be in em's, but but the script I repurposed from an old project I can't seem to get working with em's, it only seems to work with pixels.

$(window).scroll(function(){
    $("#nav").css("top",Math.max(0,96-$(this).scrollTop()));
});

Here's a demo of what it does:

http://jsfiddle.net/hwRSF/1/

If anyone can help and show me what I need to do it would be greatly appreciated!

Phinet
  • 527
  • 3
  • 14

3 Answers3

2

because scrollTop() returns in pixels, you will need to convert it into em values based on your base size.

For this particular question, it looks like your base size is 16, so you just need to divide the pixels by 16.

your navigation css:

#nav {
 ...
 top: 6em; /* 96 / 16 = 6*/
 ...
}

jquery:

$('#nav').css("top",Math.max(0,(96 - $(this).scrollTop())/16) + "em");

example fiddle: http://jsfiddle.net/hwRSF/3/

kennypu
  • 5,950
  • 2
  • 22
  • 28
  • Sorry if I'm really bad at explaining, but basically yes this is what I need, but I was hoping in the end to not have a specific font size (that it can change without having to change all the scripts). But yeah, this is great, I'll only need to edit two things! – Phinet Jul 16 '13 at 04:14
  • @PS13 what do you mean specific font size? 1em will always be 16px (usually) unless the user sets the browser font-size to something else. – kennypu Jul 16 '13 at 04:18
  • Yes, I want it to not mess up when that happens. – Phinet Jul 16 '13 at 04:20
  • in that case you would need to check out the answer here: http://stackoverflow.com/questions/7444451/how-to-get-the-actual-rendered-font-when-its-not-defined-in-css to get the browser's font size, then use that instead of 16 – kennypu Jul 16 '13 at 04:23
  • Thankyou! That's exactly it. You deserve a hug! – Phinet Jul 16 '13 at 04:26
0

It is fine to use em for top:

$("#nav").css("top", '3em');

Working fine for me with Chrome 28 on Linux Mint.

Oscar
  • 59
  • 5
  • I'm not sure what you mean by that... all that does is lock the div in place. But thanks! – Phinet Jul 16 '13 at 03:54
  • So you want to get top/left using sth like `$.scrollTop()` and but in `em` instead of `px`? – Oscar Jul 16 '13 at 04:02
0

A nice way to do this is to let the browser render 1em and then find out that value using javascript.

HTML

<div class="hidden dummy-em"></div>

CSS

/* only use hidden if you don't want the user to see it
   you can use any element with a height of 1em
   do not use display: none; */

.hidden{
    position: absolute;
    left: 500vw;
}
.dummy-em{
    height: 1em;
}

Javascript(jQuery)

// JS returns these kind of values in px
var oneEm = $('.dummy-em').innerHeight();

Avoid the math and let the browser do the work for you

Clark Nelson
  • 171
  • 1
  • 6