Place an overlay element in the top-left corner of a perfectly centered image

Currently, there is an image that is centered on the screen using flexbox:

.center-flex {
    display: flex;
    justify-content: center;
}

<div class="center-flex">
    <img id="revealImage">
</div>

An attempt is being made to dynamically create a div that should be positioned at the upper-left hand corner. Despite trying to obtain the computed left property of the image element, it returns as auto due to the flex layout.

const revealImage = document.getElementById('revealImage');

const left = window.getComputedStyle(revealImage,null).getPropertyValue('left');

let square = document.createElement('div');
square.style.height = '100px';
square.style.width = '100px';
square.style.zIndex = '2';
square.style.position = 'absolute';
square.style.backgroundColor = 'red';
square.style.top = 0;
square.style.left = left;

console.log('left: ' + left);

As a result, a red box is displayed properly overlaid but it still remains centered instead of being set to the left.

https://i.sstatic.net/QE1aN.png

Answer №1

One innovative method to enhance the structure of the HTML is to incorporate the picture element to enclose the red square.

Here is an illustrative example:

html:

<div class="center-flex">
    <picture>
        <img id="revealImage">
    </picture>
</div>

css:

picture {
    position: relative;
}

js:

const picture = document.querySelector('picture');

const square = document.createElement('div');

square.style.height = '100px';
square.style.width = '100px';
square.style.zIndex = '2';
square.style.position = 'absolute';
square.style.backgroundColor = 'red';
square.style.top = 0;
picture.appendChild(square)

https://jsfiddle.net/kongallis/ju16rdfL/9/

Answer №2

It appears that there may have been a minor error (if I am not mistaken):

It seems like this may be the mistake:

square.style.left = left;

Instead, should it be:

square.style.left = 0;

Is that correct?

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

Validating dropdown lists with Jquery

Custom Dropdownlist: <div class="col-md-2"> <div class="form-group"> <label for="field-3" class="control-label">Priority</label> <select id="lstpriority" class="custom-selectpicker" data-live-search="true" da ...

An improved method for fetching data from the server at regular intervals of x minutes

Is setInterval the best way to periodically check for updates in a database and update the UI accordingly, or are there better approaches that I should consider? I've read conflicting opinions on using setInterval for this purpose, with some sources ...

Divide the pair of arrays that are transmitted via JSON

I combined two arrays and passed them through JSON, as shown below: $result = array_merge($json, $json1); echo json_encode($result); Now, to retrieve the data, I am using the following code: $.getJSON('./tarefasaad52', function (data) { } How ...

The navbar toggler icon is not displaying

<header class="container"> <div class="container pt-3 col-md-5 col-sm-5 col-xs-6 text-center"> <a href="#" class="site-logo"><img src="#"></a> <button class="navbar-toggler" type="button" data-toggle="collapse" ...

What is the best way to perform a redirect in Node.js and Express.js following a user's successful login

As I work on developing an online community application with nodejs/expressjs, one persistent issue is arising when it comes to redirecting users to the correct page after they have successfully signed in. Despite reading several related articles and attem ...

Having trouble with a jquery link not working even after removing the 'disabled' class

I am currently using a script that disables links with the class "disabled" //disable links $(document).ready(function() { $(".disabled a").click(function() { return false; }); }); In addition, I have another script that toggles the disabled s ...

NativeScript element isn't showing up

Being relatively new to application development with NativeScript, I find myself in a situation where I need assistance in finding a solution. Drawing from my experience with PHP, I am now looking to create a template for each "page" of the application. Th ...

The useState setFunction does not alter on OnClick events

My useState element is causing issues because the function doesn't get called when I click on it. I've tried multiple solutions and debugging methods, but it seems like the Click event isn't being triggered no matter what I do. const [moda ...

AngularJS Vimeo API Request Error: "401 Authorization Required"

I've been experimenting with making external API calls to Vimeo from my AngularJS code using $http.jsonp. However, I keep receiving a 401 Authorization required error even though I have included my authorization key in the header. I encountered a simi ...

problem with nivo slider causing content to overflow

My webpage is using nivoslider to display images. However, I am facing an issue where the images are overflowing one by one until the page fully loads. I have tried setting the overflow:hidden property in the CSS but it doesn't seem to correct the pro ...

What is the best way to incorporate new elements into the DOM in order to allow users to share their comments

Can anyone help me with the code below? I have a text box and a comment section, along with a button to add comments. However, I need assistance with adding the posted comment below the comment section. Below is the code snippet: <div id="comments"&g ...

Selenium gets caught in endless loops

On my homepage, I have a variety of links that lead to different applications. Each link opens a new tab or window, where I need to check for the presence of a specific element using its XPath (which is provided from an Excel file for all applications). ...

Using React Native to implement Firebase onSnapshot with FlatList pagination

INTRODUCTION I have a collection of items stored in FireStore with the "date" property. On the client side, I'm using a FlatList to display these items ordered by date, starting with the most recent item at the top. The challenge I'm facing is ...

What is the best way to create a divider between tab panes in JavaFX?

I created a unique vertical tabpane, but I am struggling to insert horizontal lines between each label. Below is the code snippet I have used: .tab *.tab-label { -fx-rotate: 90; } .tab { -fx-padding: 3em 0.5em; } .tab-pane .tab-header-area .tab ...

Disabling the background shadow effect in Angular Material's Accordion

I successfully disabled the background shadow on the Angular Material Accordion in this demonstration by incorporating the following CSS rule: .mat-expansion-panel:not([class*='mat-elevation-z']) { box-shadow: none !important; /* box-shadow: ...

Having trouble displaying the selection menu when using Angular Strap?

//test.js const dropdownMenu = document.querySelector('.dropdown-menu'); dropdownMenu.addEventListener('click', (event) => { alert(`You clicked on ${event.target.textContent}`); }); // index.html <div class="dropdown"> ...

Switching jQuery on various sections of a webpage

In my attempt to replicate the functionality of Facebook's Like button, I have encountered a challenge regarding where exactly to click in order to change the button state. When the button is not liked yet, users should be able to click anywhere on t ...

One creative method for iterating through an array of objects and making modifications

Is there a more efficient way to achieve the same outcome? Brief Description: routes = [ { name: 'vehicle', activated: true}, { name: 'userassignment', activated: true}, { name: 'relations', activated: true}, { name: &apos ...

How to manage form submissions in Vue.js using inputs within child components

I'm working on a parent component that acts as a form. This form consists of multiple child components, each containing input fields. <template> <div class="form"> <generalData v-model="input" /> <textAreas v- ...

jQuery - Enhancing User Experience with Dynamic Screen Updates

Is there a way to update the screen height when resizing or zooming the screen? Whenever I zoom the screen, the arrows break. I'm also curious if the method I'm using to display images on the screen is effective. It's supposed to be a paral ...