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

Unlock the Power of jQuery Plugins: Implementing Global Settings Modifications

I have developed a jQuery plugin ( https://github.com/OscarGodson/jKey ) and some users are requesting localization support. My initial idea was to add an additional parameter in the plugin for localization, such as: $(window).jkey('?',callback, ...

The issue with element.style.backgroundColor not functioning properly within WordPress

Struggling to make the background of a button change upon hover? I've got the code, but it seems to be working everywhere except in WordPress. Check out the code that should be working here: https://jsfiddle.net/TopoX84/3oqgmjb0/ Want to see it not ...

Dealing with prompt boxes in Robot Framework: A Guide

Currently, I am utilizing the Robot Framework in conjunction with Selenium2Library for automating tests on websites. During one particular scenario, a prompt box appeared (similar to an alert but containing an input field). The challenge is that Robot Fram ...

Positioning the jQuery mobile navBar to be fixed on iOS 4 devices

Currently working on a mobile app with jquery using iOS4 and iOS5 compatibility as the final hurdle. While fixing the navigation bar is simple on iOS5 with position:fixed, it's not as straightforward on iOS4! I've experimented with various soluti ...

Utilize CSS to break apart text (text = white space = text) and align text in a floating manner, allowing

Is there a way to use CSS to create a white space in the middle of text? Currently, I am manually breaking the text, which is not ideal. I am aware that there is a function that allows the text to end and start in another div, but unfortunately, it is not ...

The Meteor update is unsuccessful on the Mongo Sub Collection and will not continue

I am currently facing an issue with updating a specific object within an array in my object based on a value. Whenever I try to add the update code, the function gets stuck at that point without proceeding further. None of the console.log calls after the u ...

MongoDB Driver Alert: MongoError - Cursor Not Found. Cursor ID 7820213409290816 was not located in the specified namespace db_name.collection_name

Having successfully created a Nodejs API server that connects to AWS MongoDB (version: 3.6), everything seems to function flawlessly when calling one specific API endpoint (api/lowest). However, upon making multiple simultaneous calls to this API (15 in to ...

Checkbox in Angular FormGroup not triggering touched state

There seems to be an issue with the Angular form when checking if the form is touched, especially in relation to a checkbox element. Despite the value of the checkbox changing on click, I am seeing !newDeviceGroup.touched = true. I'm not quite sure wh ...

Unable to view image stored as a blob

https://i.stack.imgur.com/8v90u.pngI have been studying these examples PHP display image BLOB from MySQL How to display an BLOB image stored in MySql database? They all demonstrate the same method of displaying images saved as blob. In my case, I ha ...

Looking to use regex to search through a webpage's text content written in JavaScript

I am struggling with the re.search function and how to use it effectively. I have a block of text/javascript that I need to extract in order to convert it to json using json loads. $(function() { $product = $('#product-' + 12272257171); ...

What sets apart window.app=new Vue({}) versus const app = new Vue({}) when included in app.js within a Vue.js environment?

What exactly is the difference between using window.app and const app in main.js within Vue? import question from './components/Questions.vue'; Vue.http.headers.common['X-CSRF-TOKEN'] = window.Laravel.csrfToken; window.App = new Vue({ ...

The AJAX call to retrieve data from a file dynamically is experiencing issues

I am currently trying to use AJAX to dynamically retrieve data from my PHP page and display it on my HTML page. However, I am running into some issues with getting it to work properly. You can view the page here Here is the snippet from the HTML Page wher ...

Utilizing a background image property within a styled component - Exploring with Typescript and Next.js

How do I implement a `backgroung-image` passed as a `prop` in a styled component on a Typescript/Next.js project? I attempted it in styled.ts type Props = { img?: string } export const Wrapper = styled.div<Props>` width: 300px; height: 300px; ...

The datepicker feature mysteriously vanishes when using Safari browser

When I utilize the jquery ui datepicker (range) and open my datepicker, if I scroll down the page, the calendar disappears. This issue seems to only occur on Safari browsers with mobile devices. Has anyone else experienced this problem? Would someone be ...

I encountered an issue when trying to include the dotenv file, receiving the following error message: [TypeError: Network request failed]

babel.config.js File plugins: [ ["module:react-native-dotenv", { "envName": "APP_ENV", "moduleName": "@env", "path": ".env", "blocklist": null, "allowlist": null, "blacklist": null, // DEPRECATED "whitelist": ...

Preventing the "save" button from being enabled until a change has been made to at least one input field

I have a page with approximately 20 input fields, along with save and register buttons. Is there a way to activate the "save" button only when a change has been made in at least one of the fields? ...

Enhancing Values Across a Timeframe Using JavaScript

Last time, I asked about my code. Here is what I have currently: var secs = 100; setInterval(function() { var $badge = $('#nhb_01'); $badge.text((parseFloat($badge.text())+0.01).toFixed(2)); }, secs); I want the counter to increase by ...

Show items according to the side menu in Onsen-UI

After successfully populating the sidemenu with OpenCart categories and displaying products on the main page, I am facing an issue when it comes to showing specific products under a particular category. For example, clicking on 'PC' in the side ...

<div class="firstHeaderClass"> What exactly is this?

Struggling to eliminate a recurring header across all my webpages for customization, I've hit a roadblock in identifying the source of this repeating header. Upon stumbling upon this code snippet in the header section, my efforts to decipher its ...

What steps can be taken to ensure the CSS/HTML image aspect ratio remains consistent on various monitors?

My square-shaped image (1:1 aspect ratio) is displaying differently across various devices when I use the codes below. While some show it as a perfect square, others display it as a rectangle. Is there a solution to maintain the original aspect ratio consi ...