Alexander Solonik Alexander Solonik - 8 months ago 37
CSS Question

Offset of <a> tag , is off by few pixels

I wanted to create a simple dotted underline animation for a menu bar of mine , so i wrote the following HTML:

<nav role="navigation" class="navigation">

<ul class="nav-listed-links">
<li class="active"><a href="">Home</a></li>
<li><a href="">About</a></li>
<li><a href="">Our Potfolio</a></li>
<li><a href="">History</a></li>
<li><a href="">Contact US</a></li>
<li class="underline"></li>


And the following JS code to make the underline move.


$('.nav-listed-links > li > a').hover(function() {

var offset = ($(this).offset().left - 0),
width = $(this).outerWidth();


left: offset,
width: width

}, function() {



The smooth animation is CSS transitions, FIDDLE HERE.

Ok so now lets zero down on the problem , In the JS code i am try to get how far off the
is from the left of the document and so i have the following code:

var offset = ($(this).offset().left - 0)

Yet the underline is a bit off from where the start of the
tag is, see screenshot below:


Why is this happening. I am sure this is something silly , but i really have't been able to figure this out for the life in me.


With offset() you

retrieves the current position relative to the document

Therefore with the default margin of the body you have that extra gap.

I suggest the use of position() to avoid any problems, since the underline is relative to the ul container :

retrieve the current position of an element relative to the offset parent

var offset = $(this).position().left,

Updated Fiddle

Reference Position()