Position element over background image. But the BG img changes size with the window. CSS -
i have background image changes size windows size, , need position element on in same place relative background image.
how!?
css
background:url("http://placehold.it/100x100") no-repeat center center fixed; -webkit-background-size:"cover"; -moz-background-size:"cover"; -o-background-size:"cover"; background-size:"cover";
the background image covers entire background , changes size window keeps proportions having overlay.
edit - 2016
my solution pure css position element in middle , offset correctly using calc function. , resize accordingly use vmin value:
$offset-top: ...; $offset-left: ...; .element { top: 50%; left: 50%; transform: translate(calc(-50% + #{$offset-top}), calc(-50% + #{$offset-top})); width: 50vim; height: 50vim; }
what asking not trivial thing @ all, involves figuring out how background-size:cover
works , positioning element using javascript. due nature of background-size:cover
how image can flow out of x-axis or y-axis cannot done css.
here solution problem, on load , resize calculates scale of image , x or y offset , draws pointer @ relevant location.
jsfiddle (red dot in google's red 'o')
html
<div id="pointer"></div>
css
body { background:url(https://www.google.com.au/images/srpr/logo4w.png) no-repeat center center fixed; -webkit-background-size:cover; -moz-background-size:cover; -o-background-size:cover; background-size:cover; } #pointer { margin-left:-10px; margin-top:-10px; width:20px; height:20px; background-color:#f00; position:fixed; }
js
var image = { width: 550, height: 190 }; var target = { x: 184, y: 88 }; var pointer = $('#pointer'); $(document).ready(updatepointer); $(window).resize(updatepointer); function updatepointer() { var windowwidth = $(window).width(); var windowheight = $(window).height(); // largest dimension increase var xscale = windowwidth / image.width; var yscale = windowheight / image.height; var scale; var yoffset = 0; var xoffset = 0; if (xscale > yscale) { // image fits in x axis, stretched in y scale = xscale; yoffset = (windowheight - (image.height * scale)) / 2; } else { // image fits in y axis, stretched in x scale = yscale; xoffset = (windowwidth - (image.width * scale)) / 2; } pointer.css('top', (target.y) * scale + yoffset); pointer.css('left', (target.x) * scale + xoffset); }
Comments
Post a Comment