Determining the background image size of a div when the window is resized

I'm facing a problem that I can't seem to solve. I have a div with a background image.

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

I want to make a specific point of this background image clickable. I know I can achieve this by adding a div with a z-index, making it clickable, and positioning it using position:absolute, like this:

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

However, how can I ensure that this clickable point stays in the same position when I resize the window, especially if my background image needs to be responsive with background-size:100% auto?

Is there a way to calculate the height of the background image in real-time when resizing the window? Or perhaps another method I should consider? :(

Answer №1

Check out this simple and effective solution for positioning an element absolutely based on a full-width background with background-size: 100% auto.

The trick here is to set the element's font-size to 1vw (1/100th of the viewport width) and then determine its position, size, and dimensions using em units. This way, the element will resize proportionally no matter the viewport size.

Feel free to adjust the demo size, and you'll see that the box stays perfectly aligned around the cat's nose.

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

.nose {
  border: 1px solid yellow; /* just for demonstration */
  position: absolute;
  font-size: 1vw;
  top: 27em;
  left: 59em;
  width: 6em;
  height: 5em;
}
<a class="nose"></a>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When I hover over my images, they begin to flash before my eyes

My layout is set up so that when I hover over the printer image, it should switch to another image. However, instead of smoothly transitioning, the image starts to flash. This issue occurs in all browsers, indicating that I have made a mistake somewhere. ...

Tips for enabling TypeScript's static typings to function during runtime

function multiply(num: number): number { console.log(num * 10) // NaN return num * 10 } multiply("not-a-number") // result == NaN When attempting to call the function above with a hardcoded invalid argument type, TypeScript correctly identifies and w ...

Storing data in localStorage with the use of java, json, ajax, and html

I have been exploring the use of localStorage to transfer variables between pages. In my JavaScript, I am populating a List: output.add(0, accountGroup.getAccountId()); output.add(1, accountGroup.getLevel()); output.add(2, accountGroup.getGroupName()); ou ...

Avoid triggering the sum button on click after every successful AJAX call in jQuery

Hello, I apologize if my title question is not clear as I am a bit confused. Let me explain the scenario: I am creating a looping post timeline similar to Facebook, where each post has comments. The structure is as follows: ++++++++++++++++++++++++++ Po ...

Is it possible to write a text file in UTF-16 using Javascript?

I need to create a UTF-16 text file from a string. For instance: var s = "aosjdfkzlzkdoaslckjznx"; var file = "data:text/plain;base64," + btoa(s); The above code generates a UTF-8 encoding text file. How can I modify it to produce a UTF-16 text file usin ...

Creating multiple AJAX contact forms can be achieved by modifying the code to accommodate multiple forms on a single page. Here's

My one-page website features 15 identical contact forms all with the same ID, created using basic PHP. Unfortunately, I am facing an issue where AJAX is only working for the first form. When submitting any other form, it simply opens a white page with a "T ...

The <hr> tag is not displaying properly within the <option> element

I'm facing an issue with a selection element in my Vue project <div class="resultContainer"> <section> <option class="resultBtn" v-for="exchange in finalExchanges"> {{exchange}} <hr></option> </section> ...

Distinguishing between creating controllers in AngularJS

I am a beginner in the world of AngularJS and I have come across two different examples when it comes to creating a controller. However, the one that is more commonly used doesn't seem to be working for me. The problem with the first example is that ...

Issue with executing a jQuery event within a JavaScript object due to application error

I am struggling to comprehend how to set listeners in my JavaScript object. For instance: var obj = function(){ this.test = function(){ console.log('test'); } $(document).on('click','#test',(function(){ ...

The code is throwing an error because the variables error_message and success_message have not been defined for the delete button in Codeigniter using the

Currently, I am utilizing codeigniter CRUD and displaying the view using datatable after setting the theme in the crud options. $crud->set_theme('datatables'); However, there seems to be an issue with the delete button not functioning correc ...

Shift attention to the subsequent division after a correct radio option or text input has been submitted

I need to enhance the user experience on my form. When a user interacts with specific elements like hitting enter in a text input or clicking a radio button, I want to automatically focus on the next "formItem" division. My form structure is organized as ...

Steps for sending a POST request for every file in the given array

I am working on an angular component that contains an array of drag'n'dropped files. My goal is to make a POST request to http://some.url for each file in the array. Here is what I have been attempting: drop.component.ts public drop(event) { ...

Instructions for converting a MySQL select statement within a foreach() loop into an HTML form

I'm in the process of developing a course registration system for a small project. Currently, I have a table named 20182019carryovertbl from which I successfully select students who are carrying over their courses. Now, I need to transform this select ...

What is the best way to include an object within an array that is a property of another object in React.js?

Greetings, I apologize for the somewhat ambiguous title. It was a challenge to find a clearer way to express my thoughts. Currently, I am engrossed in my personal project and have encountered a particular issue. I would greatly appreciate any advice or gu ...

The LoopBack framework encountered an issue where it could not execute the 'post' method due to being undefined

As a newcomer to loopback and node.js, I have successfully created two models - Rating and RatingsAggregate. Utilizing the loopback explorer, querying and posting against the API has been smooth. In an attempt to establish basic business logic, I am curre ...

The first item in Swiper is incorrectly displayed after the initial cycle, even though the data is accurate

Currently, I am incorporating the slider functionality in Vue using the Swiper framework. Although everything seems to be functioning properly, there is a minor issue that arises when filtering the data and completing the first cycle after scrolling. The f ...

What is the best way to adjust the spacing in my bootstrap Navbar? I am struggling to make it stretch to the entire width of the screen

I am currently working on a website project where I want to have a navigation bar that spans the full width of the screen with a black background. I also need the links to be centered and evenly distributed within the navbar. My main issue right now is re ...

Creating a visual representation on a canvas using JQuery

$.fn.colorPicker = function () { const $div = this; const $colorPickerIcon = $("<img></img"); const $canvas = $("<canvas></canvas>").addClass("canvas"); const $context = $canvas.getContext("2d"); const $closeButton ...

Pressing the submit button will not successfully forward the form

I've encountered an issue with my submit buttons - when I click on them, nothing happens. They were functioning properly before, but now they seem to be unresponsive. What could be causing this problem? <form id="contact" name="updateorder" acti ...

Switch between divs based on the current selection

var header = $("#accordion"); $.each(data, function () { header.append("<a id='Headanchor' href='javascript:toggleDiv($(this));'>" + this.LongName + "</a>" + "<br />", "&l ...