Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How calculate div background image size on resize window

i have some problem which i can't figure out. so i have a div with background image.

<div class="a"></div>

and i want to make clickable some point of this background image. It's okey i can make this with adding to some div width z-index and make it clickable and positioning this with position:absolute e.g,

<div class="b">
<a class="clickablePoint" href="#"></a>
</div>

but how i can keep this clickable point on the same way when i resize the window if my background-image must be a responsive so background-size:100% auto.

maybe have some method to calculate background image height realtime when resize window ? or any other method? :(

like image 640
user3348410 Avatar asked Nov 08 '22 03:11

user3348410


1 Answers

Here's a minimal viable solution showing how to absolutely-position an element based on a full-width (background-size: 100% auto) background.

I'm setting the font-size of the element to 1vw (1/100th of the width of the viewport) and then calculating its left/top position and width/height size in em units, which become equivalent to a multiple of that 1vw.

As such, resizing this demo to any size will keep the box in the same place around the cat's nose.

body {
  background: url('https://i.imgur.com/sVz3YRx.jpg');
  background-size: 100% auto;
  height: 50vw; /* for stack snippet height */
  position: relative;
  margin: 0;
}

.nose {
  border: 1px solid yellow; /* for demo */
  position: absolute;
  font-size: 1vw;
  top: 27em;
  left: 59em;
  width: 6em;
  height: 5em;
}
<a class="nose"></a>
like image 116
Jon Uleis Avatar answered Nov 14 '22 23:11

Jon Uleis