Adjust the position of elements based on their individual size and current position

I am faced with a challenge regarding an element inside a DIV. Here is the current setup...

<div id="parent">
    <div id="child"></div>
</div>

Typically, in order to center the child within the parent while dynamically changing its size, I would implement the following solution...

$('#child').resizable({
        resize:function(){
            // This adjusts the left/top offset as the width increases
            $('#child').css({
                left:$('#parent').width()/2 - $('#child').width()/2,
                top:$('#parent').height()/2 - $('#child').height()/2
            })
        }
    });

The method described above works well, although when resizing the child element, it always starts from the same initial position rather than its existing offset.

Now, I am looking for a way to modify the child's left and top offset using similar calculations as before, but this time based on the precise offset and dimensions of the child itself, not relying on the parent's dimensions.

Answer №1

Consider utilizing the transform property along with transform-origin.

The transform property affects the element's own properties rather than those of its parent.

CSS Hover

#parent {
  height: 200px;
  background: lightgray;
}
#child {
  position: relative;
  top: 50%;
  left: 50%;
  width: 100px;
  padding: 30px;
  background: red;
  text-align: center;
  transition: transform 0.5s;
  transform: translate(-50%,-50%);
  transform-origin: center top;        /* specifies origin for scaling */
}
#child:hover {
  transform: translate(-50%,-50%) scale(1.5);
}
<div id="parent">
    <div id="child">Hover me</div>
</div>

jQuery Hover

$(document).ready(function() {
  $("#child").hover(function() {
    $(this).css("transform", "translate(-50%,-50%) scale(1.5)");
  }, function() {
    $(this).css("transform", "translate(-50%,-50%)");
  });
});
#parent {
  height: 200px;
  background: lightgray;
}

#child {
  position: relative;
  top: 50%;
  left: 50%;
  width: 100px;
  padding: 30px;
  background: red;
  text-align: center;
  transition: transform 0.5s;
  transform: translate(-50%, -50%);
  transform-origin: center top;          /* specifies origin for scaling */
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="parent">
  <div id="child">Hover me</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

JavaScript: Creating an array of images from a directory

I've encountered a problem that has proven to be more complex than expected - I am struggling to find resources related to my specific question. My goal is to store 36 images from a folder on my computer into an array using Javascript. Below, you will ...

Encountering a parseJSON error on Internet Explorer 9

Is the error in Internet Explorer 9 caused by jQuery or my script? The issue arises with the parseJSON function: parseJSON: function( data ) { // Attempt to parse using the native JSON parser first if ( window.JSON && window.JSON.parse ) { ...

Putting together Modular Client-side JavaScript

Is there a way in Node.js to dynamically "require()" javascript files similar to PHP's require function? It would be great to use this feature in my client-side code for development purposes without actually calling a specific javascript function. Rat ...

jQuery accordion is currently in the expanded state

I'm currently in the process of creating an accordion using jQuery, following this example: http://docs.jquery.com/UI/Accordion The structure remains the same: <div id="accordion"> <h3><a href="#">First header</a></h3& ...

Using a dynamic image source in an Ionic 3 background

I am using ngFor to display a list of posts, each of which should have a unique background image. The getBackgroundStyle function is responsible for extracting the URL of the image from the post array. <div class="singlePost" *ngFor="let post of da ...

Achieve inline or floating displays seamlessly without the need for media queries to prevent breaking

Whenever I attempt to apply float left or display inline, it causes issues. The form currently has a max-width of 1000px. I was hoping that the first and last names would automatically align side by side if there is enough space. Perhaps setting a min-widt ...

The JavaScript code does not call an external function to retrieve data from the database

I'm currently facing an issue with retrieving the same version data from my MySQL (MariaDB) Server. In order to streamline the process and improve maintenance, I decided to create a single connection Object to manage all database queries. However, I&a ...

Determine if a webpage forwards to a new link with the help of phantomjs, flagging any issues exclusively for designated websites

As a beginner in frontend development, I have a question that may seem simple. Please be patient with me. var page = require('webpage').create(), system = require('system'); if (system.args.length === 1) { console.log('Usage: ...

Warning: MaxListenersExceededNotification may occur during the installation or creation of Node.js projects on macOS

Encountering a warning message while attempting to set up or generate Node.js projects on macOS (darwin): (node:80101) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 close listeners added to [TLSSocket]. Use emitter.setMaxList ...

Direction of Scrolling

Is it possible to have a div move in the opposite direction of mouse scroll, from the top right corner to the bottom left corner? Currently, it is moving from the bottom left to the top right. #block { position: absolute; top: 400px; left: 100px; < ...

Vue 2 checkbox form array data

Creating a checkbox list with a dynamic id and name: Data: yards[{id:1,name:'test'}] etc HTML: <ul class="checkbox-list"> <template v-for="(yard, index) in yards"> <li> ...

Strange response received from Stack Overflow API request

Having some issues with the code I'm using to call the Stack Overflow API: var request = require('request'); var url = 'http://api.stackexchange.com/2.2/search?order=desc&sort=activity&tagged=node.js&intitle=node.js&sit ...

The routing is not functioning properly as anticipated

Here is a route definition that I am using: routes.MapRoute( "FormPreview", "Forhandsgranska/{FormId}/{action}/{id}", new { controller = "FormPreview", action = "Introduction", id = UrlParameter.Optional } ...

The waypoints.js snippet seems to be malfunctioning in this specific context

After experimenting with waypoints.js (jQuery.waypoints) for some time, I've been attempting to utilize this library to incorporate animations on children elements within a specific container. Here is the approach I have taken: var waypoints = $( ...

Can I substitute custom tags for the traditional <p> tag?

My HTML with CSS has an issue where a custom HTML tag is not displaying the text while my CSS picks up another tag. Interestingly, replacing <title>Layout Controls</title> with <p>Layout Controls</p> resolves the problem and shows t ...

When I use `console.log` with `req.body` in Node, the password is

Currently, I am utilizing NodeJs on the backend to console.log(req.body) data from a form that gathers usernames and passwords from users. I have noticed that this method exposes the collected username and password information. Should I be concerned abou ...

Hide a div when multiple classes are filtered using jQuery

I have several divs with the class .item. When the user clicks on the Classfilter submit button, all .item elements that also have at least one class from the dateClasses array (for example ['28.09.2015', '29.09.2015']) should be hidden ...

How to use Angular 2 to communicate with JavaScript API whenever the router switches to

I am currently working on an Angular2 component that has a template which relies on JavaScript calls to load various components such as Facebook, Google Maps, and custom scripts. The necessary scripts are already loaded in the index.html file, so all I ne ...

Tips for Dynamic Importing and Rendering of Components in ReactJS

I'm looking to dynamically import and render a component in React. I have two components - Dashboard and Home. Essentially, I want to dynamically render the Dashboard Component inside the Home Component without having to import it beforehand or maybe ...

Greetings! I am interested in injecting HTML elements into a DOM using PHP and the jQuery Ajax method

After trying the following code snippet: $.ajax({ url: 'cod.php', type: 'POST', dataType: 'html', success: function(res){ $("#tests").html(res); } I implemented a foreach loop in my PHP s ...