suri
suri

Reputation: 363

How do i retrieve a div`s top value in pixels if it is set in percentage in css?

I have this div, which needs to be relative and the top in %:

#adiv {
    position: relative;
    top: 50%;
    margin-top: 0px;
    height:200px;
    background-color:black;
}

Now i want to find the value of top:50% in pixels. If I do this:

alert("TopHeightInPixels:"+(parseInt($("div#adiv").css("top"))));

Firefox outputs the actual pixels (100px), while Safari outputs just 50. I know why Safari does that (with my code it just stripes the % of my 50%, I guess), but how do I do it right?And if I do this using jQuery:

alert("TopHeightInPixels:"+(parseInt($("div#adiv").offset().top)));

or

alert("TopHeightInPixels:"+(parseInt($("div#adiv").position().top)));

I get a value of 0. So how do I do it the right way? Thanks in advance! Here's the fiddle.

Upvotes: 3

Views: 3792

Answers (3)

Hitesh Modha
Hitesh Modha

Reputation: 2790

Try this

$('#adiv').offset().top

Upvotes: 0

jb10210
jb10210

Reputation: 1176

The top attribute sets your position relative to its parent, but the parent needs to have a height in order for this to work using percentages.

See jsFiddle.

Upvotes: 1

Michael Allen
Michael Allen

Reputation: 5828

See the answers to this question: Detecting the position of a div

The top of a div is its y coordinate usually. Unsure if the box model allows offsetting of the origin point of a div but I'm pretty sure it doesn't.

Upvotes: 1

Related Questions