In my coding project, I've encountered a situation where I have 3 "pins" positioned within a div
called #outerdiv
. This div
has a background-image
and the pins are supposed to remain in the same spot on the background image no matter how the window is resized. Interestingly, this works perfectly fine with #pin1
, but not with #pin2
and #pin3
, despite them having similar code. The key distinction seems to be that #pin1
comes first in the HTML structure.
UPDATE: You can view the JSFIDDLE for better clarity.
Upon resizing the window, it's evident that while #pin1
maintains its position flawlessly on the background image, #pin2
, along with subsequent pins, gets slightly displaced downwards, causing them to lose alignment with the background image. However, they still seem to be correctly aligned horizontally.
$(document).ready(function(){
updateProductBg();
});
$(window).resize(function() {
updateProductBg();
});
function updateProductBg(){
if($(window).width()/$(window).height() >= 2600/1450) {
$('#outerdiv').css({'height':'100%','width':$(window).height()*(2600/1450)+'px', 'margin-left':-$('#outerdiv').width()/2+'px', 'left':'50%', 'top':'0', 'margin-top':0});
} else {
$('#outerdiv').css({'height':$(window).width()*(1450/2600)+'px', 'width':'100%', 'margin-left':0, 'left':0, 'top':'50%', 'margin-top': -$('#outerdiv').height()/2+'px'});
}
}
#outerdiv {
background-image: url(https://upload.wikimedia.org/wikipedia/commons/6/6a/Luftaufnahmen_Nordseekueste_2013_05_by-RaBoe_314.jpg);
background-size: contain;
background-repeat: no-repeat;
background-position: 0 0;
position: absolute;
bottom: 0;
width: 100%;
height: 100%;
}
.pin {
background-image: url(https://upload.wikimedia.org/wikipedia/commons/1/16/WP_SOPA_sm_icon_identica_ffffff.png);
width: 32px;
height: 33px;
position: relative;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="outerdiv">
<div id="pin1" class="pin" style="top:21%; left:38%;"></div>
<div id="pin2" class="pin" style="top:13%; left:24.5%;"></div>
<div id="pin3" class="pin" style="top:36%; left:26%;"></div>
</div>
updateProductBg()
function is utilized to ensure that #outerdiv
matches the dimensions of the background-image
. To test it out yourself, simply substitute the 2600
and 1450
values with your actual image width
and height
.