Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easily position an element over another element in jQuery?

Tags:

jquery

element

I need to position a div over an image with jQuery. I can create it with using position: fixed and use top and left to position it using elements offset, but it sucks because the element will not be on top of the element if user scrolls.

Any other ideas?

like image 806
Martti Laine Avatar asked Apr 18 '10 10:04

Martti Laine


People also ask

How do you position an element on top of another element?

You can use the CSS position property in combination with the z-index property to overlay an individual div over another div element. The z-index property determines the stacking order for positioned elements (i.e. elements whose position value is one of absolute , fixed , or relative ).

How do I set relative position in jQuery?

jQuery position() MethodThe position() method returns the position (relative to its parent element) of the first matched element. This method returns an object with 2 properties; the top and left positions in pixels.

How do you position something relative to another div?

First set position of the parent DIV to relative (specifying the offset, i.e. left , top etc. is not necessary) and then apply position: absolute to the child DIV with the offset you want. It's simple and should do the trick well.

What is position in Javascript?

The position property sets or returns the type of positioning method used for an element (static, relative, absolute or fixed).


1 Answers

If you're doing this multiple places, you can do this:

<div style="position: relative;">
  <div style="position:absolute; width: 276px; height: 110px; z-index: 2;">
    Content here will be on top the image
  </div>
  <img style="width: 276px; height: 110px;" src='http://www.google.com/intl/en_ALL/images/logo.gif' alt="Test Img" />
</div>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​

If you match the height/width style attributes on the inner/ouer divs, the inner <div> comes before the <img /> and you give the inner <div> a higher z-index than the image, it'll perfectly overlap the image.

You can see an example of this in action here: http://jsfiddle.net/ZcBus/

like image 149
Nick Craver Avatar answered Sep 18 '22 11:09

Nick Craver