hguser
hguser

Reputation: 36028

how to set the position of a element based on it's parent

hi I have a div which contains just a image like this :

(div)
    (img. …)
(/div)

Now,I want to create a mark in the image ,s I use :

$(div).append((img src =mark.jpg id =mark)).

then set its position :

$(div img#mark).position(…)

Here I don't know how to set it.

I just want to make the mark's position within its parent .

In fact ,what I want like the google map ,when you search something in google map ,the results will be marked in the map .

Of course,my require is much easy.

I have thought to get the offset of the parent ,then caculate the really position of the mark image .

But I can't make it. Any idea ?

Btw ,I ask this in my phone ,so I can't make a pretty format.

Upvotes: 5

Views: 5023

Answers (4)

hardyharzen
hardyharzen

Reputation: 81

If I read you correctly, the desired effect should be achievable with plain css:

#container {
  position:relative;
}
#mark {
  position:absolute;
  left: [to your liking] px;
  top: [to your liking] px;
}

PS: Oh well, only 3 ppl beat me to it.

Upvotes: 1

Bjorn
Bjorn

Reputation: 5362

I think you don't need jQuery to do this:

div {
  position: relative;
}

img#mark {
  position: absolute;
  top: 10px;
  left: 10px;
}

This way, img#mark will be positioned relative to div's position:

+---------------
| div
|    ___________
|   | img#mark
|   |
|   |
|    -----------
|
+---------------

Upvotes: 1

Matt Asbury
Matt Asbury

Reputation: 5662

$("div").css('position', 'relative');
$("div img#mark").css({
    position: 'absolute',
    top: '0px',
    left: '0px'
});

Change top and left values to suit where you would like to position the mark.

Upvotes: 1

polarblau
polarblau

Reputation: 17734

You could use CSS:

div { position: relative; }
div img#mark { position:absolute; }

And then set the position like this:

$("div img#mark").css({
    'top': '10px',
    'left': '10px'
});

Does that do what you meant?

Upvotes: 5

Related Questions