Search code examples
javascriptjquerycssimageposition

Responsively position an image at specific target over background image


I have a responsive background image with a smaller image positioned over it. I am trying to keep the smaller image at a specific location when the window is resized.

Both images scale properly, and the left position works so far, but not the top position.

img {
max-width:100%;
}

#dot {
position: absolute;
top: 17%;
left: 66.5%;
width: 10%;
height: 0;
padding-bottom: 10%;

}

I have found some questions with answers that suggest:

Vertical Alignment or Positioning with Javascript

I've also looked into .position() and .offset(), not sure if either would work.

I think my best solution would be to calculate the Y offset using the current window height as a reference but I am not sure what my JS or Jquery code should look like.

Here is my jsfiddle:

http://jsfiddle.net/melissadpelletier/xBu79/21/


Solution

  • You are definitely gonna need some javascript for this. What you can do is calculate the height and width of the image whenever you resize your browser window. Then simply use some math to calculate the position of the dot relative to those dimensions.

    var height = $('#image').height();
    var width = $('#image').width();
    
    /* change the fractions here according to your desired percentages */
    $('#dot').css({left: width/2, top: height/2});
    
    $(window).resize(function() {
        height = $('#image').height();
        width = $('#image').width();
    
        /* change the fractions here according to your desired percentages */
        $('#dot').css({left: width/2, top: height/2});
    });
    

    Try this code: http://jsfiddle.net/LimitedWard/FFQt2/3/

    Note that you will need to also resize the dot according to the height/width of the image if you want it to always fit inside that box.

    Edit: after further investigation, it is possible to do this in CSS; however, it's a lot sloppier because the dot doesn't follow the image if the window is too wide. This jQuery solves that problem by using pixel-based positioning.