Positioning a div beside another div without containing it

Check out the snippet below.

I am looking to vertically center an element, 'modal', over another div, 'element', regardless of its position or margins. However, I cannot place the 'modal' div inside the 'element' div due to restrictions with the react component I am working on. I am wondering if there is a way to position one div relative to another without nesting them. Should I use javascript to detect the position of the 'element' div or are there any pure CSS solutions available? Thank you.

.container {
  border: 2px solid red;
  margin: 5rem;
  height: 20rem;
  width: 20rem;
  position: relative;
}

.element {
  background: pink;
  height: 10rem;
  width: 10rem;
  margin: 3rem;
}

.modal {
  position: absolute;
  background: green;
  height: 2rem;
  width: 2rem;
}
<div class="container">
  <div class="modal" />
  <div class="element" />
</div>

Answer №1

By imposing the condition of "regardless of where it is or what margin it has," the number of possible solutions is significantly limited. In this scenario, a JavaScript solution seems to be the only feasible option.

If both elements share the same offset parent (closest with position: relative), you can develop a function that calculates the center of the .element and adjusts the modal's position based on its dimensions:

// Function to centrally position an element in relation to another
function centerElement(el, rel) {
  var offset = getOffset(el);
  var center = getCenterPoint(rel);
  el.style.top  = center.top  - offset.height / 2 + 'px';
  el.style.left = center.left - offset.width  / 2 + 'px';
}

// Retrieve the central point of an element
function getCenterPoint(el) {
  var elOffset = getOffset(el);
  return {
    top:  elOffset.top  + elOffset.height / 2,
    left: elOffset.left + elOffset.width  / 2
  };
}

// Obtain the offset values of an element
function getOffset(el) {
  return {
    top: el.offsetTop,
    left: el.offsetLeft,
    width: el.offsetWidth,
    height: el.offsetHeight
  };
}

// Example of usage
var element = document.querySelector('.element'),
    modal   = document.querySelector('.modal');

centerElement(modal, element);
.container {
  border: 2px solid red;
  margin: 5rem;
  height: 20rem;
  width: 20rem;
  position: relative;
}

.element {
  background: pink;
  height: 10rem;
  width: 10rem;
  margin: 3rem;
}

.modal {
  position: absolute;
  background: green;
  height: 2rem;
  width: 2rem;
}
<div class="container">
  <div class="modal"></div>
  <div class="element"></div>
</div>

Answer №2

Using CSS-Grid for layout:

.container {
  border: 2px solid red;
  margin: 1rem auto;
  height: 20rem;
  width: 20rem;
  position: relative;
  display:grid;
  place-items:center;
  
}

.modal, .element {
grid-row:1;
grid-column:1;
}

.element {
  background: pink;
  height: 10rem;
  width: 10rem;
  margin: 3rem;
}

.modal {
  background: green;
  height: 2rem;
  width: 2rem;
  z-index:1;
}
<div class="container">
  <div class="modal"></div>
  <div class="element"></div>
</div>

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

Issue with Ajax function's communication with server

Currently, I am working on integrating an uploader script called dropzone.js into my website. Uploading files to the server is functioning correctly, but I am encountering issues with deleting them. Below is the JavaScript code I am using: $(document).rea ...

Redirect user if the parameter does not match the corresponding ID in the database using React Router V4

I need to handle the scenario where there is no matching lockId in my database by redirecting to the home route. I am retrieving locks from my Redux state. The following implementation achieves this: const lockId = this.props.match.params.lockId const lo ...

An issue arises with an unterminated string literal whenever I attempt to click on an anchor

Upon clicking a tag, the following error occurs unterminated string literal <a onclick="ga('send', 'event', 'CloudStore', 'Click', 'Cloud is here - Banner’);" href="about.php" class="red-text block"> ...

Is a middleware function required for Router.use?

Currently, I'm in the process of organizing my login routes by storing them in a separate JS file named login_routes.js However, an error keeps popping up that states: TypeError: Router.use() requires middleware function but got a Object at ...

Unexpected malfunction in CSS Grid within Flexbox layout

After extensive testing, I have found that the .articleWrapper for post child items scales correctly when used on its own. However, as soon as I place this .articleWrapper inside another wrapper-element with display: flex, it loses its ability to scale hor ...

Step-by-step guide to creating a clickable div

Having an issue with around 200 clickable buttons on my website, all designed the same: <div> <asp:hyperlink> //or LinkButton </div> The background-style of the button is within the Div and the text of the button is in Hyperlink / LinkB ...

Unitary Individuals and the Connection Automation

It is advised to refrain from using the deprecated com.sun.star.frame.Desktop type and opt for the com.sun.star.frame.theDesktop singleton instead. Various programming languages provide access to singletons. For instance, in Java, this thread mentions the ...

What is the process for the Rebol programming language to independently implement an asynchronous pluggable protocol for reading

This post outlines the process of incorporating an asynchronous pluggable protocol in Rebol that can be accessed through Firefox, Internet Explorer, or the command line For instance, if I were to define the reb:// protocol, I could enter it into a browser ...

Querying Mysql Data using Select Statement in Node.js

Hey there, I want to create an SQL clause using the following function function selectFrom(reqContents, callback) { connection.query('SELECT ?? FROM ?? WHERE ?', [ reqContents.attribute, reqContents.table, reqContents.GET ], function(err ...

How can I replicate the function of closing a tab or instance in a web browser using Protractor/Selenium?

I want to create an automated scenario where a User is prompted with an alert message when they try to close the browser's tab or the browser itself. The alert should say something like "Are you sure you want to leave?" When I manually close the tab ...

Sending data to a function that is generated dynamically within a loop

How can I ensure that the date2Handler is triggered with the corresponding date1 and date2 values from the month in which the date1 change occurred? Currently, whenever the date1 value is changed in any month, the date2Handler is called with the "month" t ...

Creating a custom date format in JavaScript can easily be achieved

Need assistance with generating date in a specific format using javascript. The desired format is "2017-12-07T14:47:00+0530". I attempted to use the moments library but encountered an issue with the time zone field. moment().format('YYYY-MM-DDTHH:mm: ...

Having trouble displaying options in VueJS Component using datalist

Currently, I am harnessing the power of VueJS and its components to create an extensive array of datalists and selectors, each equipped with a submit button for validation upon form submission. Initially, I successfully implemented a datalist within a com ...

The node.js server is unresponsive and seems to be offline

I am relatively new to working with Node.js and I am currently attempting to create a basic server for an iOS notes app. However, I am facing an issue where nothing happens when I type in 'node server.js' in the command prompt. ` // SET UP A NO ...

The share-modal.js file is throwing an error because it is unable to read properties of null, particularly the 'addEventListener' property, at

I encountered an error that I want to resolve, but it's proving to be quite challenging. Despite extensive searching on Google, I haven't found a solution yet. Uncaught TypeError: Cannot read properties of null (reading 'addEventListener&apo ...

Is there a way to minimize superfluous re-renders in React without resorting to the useMemo hook?

I am currently evaluating whether I should adjust my strategy for rendering components. My current approach heavily relies on using modals, which leads to unnecessary re-renders when toggling their visibility. Here is a general overview of how my componen ...

Client.on facing issue with receiving data upon initial connection

Currently, I am utilizing the net module in order to establish a connection between my client and server. Below is the code snippet: const Net = require('net'); client = Net.connect(parseInt(port), host, function() { co ...

Fastify Node - delivering images from the upload directory

Allow access to files/images when visiting localhost:8000/properties/files/[image name] localhost:8000/properties/files/1635843023660-profile.jpg File Organization node_modules src/ uploads/ 1635843023660-profile.jpg 1635843023668-home.jpg ... . ...

conducting a validation using ajax when submitting

Currently, I am exploring the implementation of AJAX validation within a submit() handler for a web form. The AJAX functionality is executed using $.ajax() from jQuery. While setting async: false yields successful results, it triggers a deprecation notice, ...

XML and numerous, distinct DIV elements

Is it possible to display content from an XML file in a DIV upon clicking, without using IDs and involving multiple DIVs? For instance, when clicking on the first link in the following code snippet, the content from an XML file should only appear in the r ...