2

I am using the jQuery $('selector').css('top') to get the top value to help position dynamic elements and I find that I get different results based on the browser.

if the selector style is set to top:5%

Firefox returns 5%.

IE 7, 8, 9 return a pixel value that changes depending on the WIDTH of the browser screen (wow).

Chrome returns 'auto'.

in the following test html, firefox returns:

m1 - 5%
m2 - 100%
m3 - 100px

IE 7, 8, 9 returns:

m1 - 25px
m2 - 509px
m3 - 100px

and if I widen the screen, IE returns:

m1 - 49px
m2 - 977px
m3 - 100px

Chrome returns:

m1 - auto
m2 - auto
m3 - auto



<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<style type="text/css">
#m1 {top:5%;}
#m2 {top:100%;}
#m3 {top:100px;}
</style>
<title>CSS Test</title>
</head>
<body>
<div class="m" id='m1'>m1</div>
<div class="m" id='m2'>m2</div>
<div class="m" id='m3'>m3</div>

<script type="text/javascript">
function get_css() {
    var output = "";
    $('.m').each(function(){
        output +=  $(this).html() + ' - ' +$(this).css('top')+ "<br />";
    });
    $('#output').html(output);
}
</script>
<br /><input type='button' name='get_css' value="css('top')" onclick="get_css()"/>
<p><div id='output'></div></p>
</body>
</html>
sdfor
  • 6,324
  • 13
  • 51
  • 61

2 Answers2

7

Use $('selector').offset().top to get the numeric value of the top position.
.css() returns the CSS value of the top-position, which could be auto, 1234px, or something similar - not a reliable method to get the top position.

See also:

Rob W
  • 341,306
  • 83
  • 791
  • 678
0

The thing is, none of your test elements actually have dynamic positioning. See this question: jQuery .css("left") returns "auto" instead of actual value in Chrome

Community
  • 1
  • 1
Ry-
  • 218,210
  • 55
  • 464
  • 476
  • yes, that's true in the example, though when you add dynamic positioning IE still returns a px value instead of the %. I will read the post thanks – sdfor Oct 25 '11 at 15:42