For example I have two div containers like the one below:
^^^^^^^^^^^^^^^^^^<br/>
DIV 1 container|<br />
%%%%%%%%|
^^^^^^^^^^^^^^^^^^<br/>
DIV 2 container|<br />
%%%%%%%%|
The first one (Div1) is one top of Div 2.
I would like to float an icon on one of these div corners (top-left, top-right,bottom-left,bottom right).
For the first div, it would be pretty easy since I could use jQuery to get the width and height of the div and compute the corner coordinates. So for example if the first div dimension is:
1240 =width
375= height
I get these dimensions using jQuery:
var heightdiv1=$('div1').height();
var widthdiv1 = $('div1').width();
The following are the coordinates computed in JS:
Compute Bottom right coordinates:
left=1240-1240*0.1=1116=
top=375-375*0.1=337.5
Compute Bottom left coordinates
left=0
top=375-375*0.1=337.5
Compute Top right coordinates:
left=1240-1240*0.1=1116
top=0
Compute Top left coordinates:
left=0
top=0
Then I could append the icons to the div using jQuery and using the position:absolute to get that floating effect:
$('#div1').append('<a href="#"><img src="/test/icon.jpg" style="position:absolute; top: '+top+'px; left: '+left+'px"></a>');
This recipe works perfectly but only for the first div. For the second div (DIV2) or any other div in the page, it won’t land on the correct corners.
I believe i can still get the correct div dimension for any other divs but I find it hard how to position my icon on their specific corners like what I did on the first div.
I’ve tried using .offset() but I don’t know if it can compute the corner positions. If anyone can give some tips, it would be highly appreciated. Thanks.
Give the div elements
position:relativeand give the anchor (not the img) element that you’re appendingposition:absolute.When you use absolute positioning it is still relative to the nearest “positioned” (i.e., not
static) ancestor, so for your purpose you don’t need to calculate any offsets.(And, not necessary to make it work but much neater, rather than using an inline style on the elements you’re appending just give them a common class.)
Demo: http://jsfiddle.net/mSLRN/