jQuery .position() absolute or position relative to the parent

The .position() method gets the position of an element relative to the offset parent or gets the absolute position of the element. Also check jQuery .offset().

JS:

<script>
$(function(){
    var position = $('.target').position();
    $('.target').append( ": left=" + position.left + ", top=" + position.top );
    
    var position_absolute = $('.target-absolute').position();
    $('.target-absolute').append( ": left=" + position_absolute.left + ", top=" + position_absolute.top );
});​
</script>

css:

<style>
.parent {
    padding:20px;
    margin:8px;
}
.target {
    margin:15px;
    padding:3px;
}

.parent-relative {
    position:relative;
}
.target-absolute {
    margin:20px;
    padding:3px;
    position:absolute;
    left:10px;
    top:5px;
}
​
</style>

html:

<div class="parent"><h3 class="target">get position relative to the offset parent with jQuery</h3></div>
<div class="parent-relative"><h3 class="target-absolute">get absolute position of the element with jQuery</h3></div>

Leave a Comment