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

Incorporating photos within the layout of a Twitter Bootstrap grid

Looking to showcase images like the ones found here: https://i.stack.imgur.com/eD4GD.jpg These images are original and come in various sizes. I want a hover effect that includes blur, fogging effects, and text placed in the middle of the picture. Check ou ...

What is preventing this from retrieving the source code?

I'm trying to retrieve the HTML source code from http://yahoo.com/(index.html) and display it in a dialog box using this code snippet: $.ajax({ url: 'http://yahoo.com', success: function(data) { alert(data); } }); Unfortunately, ...

JSFiddle showcasing the Bootstrap grid system

I'm having trouble implementing bootstrap's grid system on jsfiddle. Check it out on jsfiddle I've tried using the example from the bootstrap documentation: <div class="row"> <div class="col-md-1">.col-md-1</div> ...

The changes made in the CSS file are not reflected in the browser

Recently, I encountered a strange issue with my new server where the CSS changes were not reflecting in the browser. Despite trying to refresh and clear the cache, the problem persisted. To investigate further, I used FileZilla to check if the updated CSS ...

What is the process for exporting a plugin from dayjs() in JavaScript?

Currently, I have incorporated the plugin isToday() to enhance the capabilities of dayjs(). Nevertheless, I am uncertain about how to export isToday() in order to utilize it across other files. import isToday from "dayjs/plugin/isToday"; expor ...

Having trouble sending data from AJAX to PHP

My goal is to implement a "load more" feature in my web app that automatically calls a PHP file to load additional products as soon as the page is fully loaded. In order to achieve this, I am using AJAX to call the PHP file: $(document).ready(function() { ...

JavaScript and CSS tabs with smooth transition effect

I want to create tabs that smoothly fade between each other when switching. The code I have works, but there's a slight issue. When transitioning from one tab to the previous one, there is a momentary glitch where the last tab briefly changes state be ...

Issue with .env file access token: Successfully working for one API in Next.js, but failing for

I am utilizing two different APIs, WordsAPI and Spotify API. Each API requires an access token or key which I have stored in a secure .env file. I have successfully fetched data from WordsAPI using the same method in getStaticProps, but I am facing issues ...

Ways to confirm the actual openness of Express app's connection to MongoDB?

I'm currently developing an Angular 7 application that utilizes MongoDB, Node.js, and Express. One issue I encountered is that if I start my Express app (using the npm start command) before connecting to MongoDB (using the mongod command), the Express ...

Issue with jQuery slider failing to slide in some situations

Check out the code on jsfiddle It seems like there might be an issue with the slide function: slide: function( event, ui ) { var input = this.next(':input'); input.val(input.attr('alt') + ui.value); } ...

Transform a group of objects in Typescript into a new object with a modified structure

Struggling to figure out how to modify the return value of reduce without resorting to clunky type assertions. Take this snippet for example: const list: Array<Record<string, string | number>> = [ { resourceName: "a", usage: ...

What is the best method for directing a search URL with an embedded query string?

Currently, I am developing an express application that has two different GET URLs. The first URL retrieves all resources from the database but is protected by authentication and requires admin access. The second URL fetches resources based on a search para ...

Tips for composing a hyperlink within a property

I'm a newbie to Vue.js and facing a challenge with assigning a property to a link. I'm unsure of how to write the "counter" variable from "data" in order for it to properly function as intended. export default { name: 'app', data ( ...

Why does Drupal's Advagg display several css and js files?

After installing the Advag module, I noticed that it is combining files, but there seems to be an issue: <link type="text/css" rel="stylesheet" href="/sites/default/files/advagg_css/css__sqX0oV0PzZnon4-v--YUWKBX0MY_EglamExp-1FI654__IOPiOtulrIZqqAM0BdQC ...

Analyzing various PHP $_POST keywords for validation

Currently, I am facing an issue with a page where a script is supposed to check if the POST request contains a certain keyword when a link is called. However, no matter how I arrange the code, it does not seem to work as expected. <?PHP if($_POST[&apo ...

Semi-Transparent Photo Slideshow

Currently, I am in the process of developing a Pokedex-like feature for a project that I am working on. The functionality is working as expected, but there is one particular feature that I would like to implement. My goal is to display only certain element ...

Seeking a breakdown of fundamental Typescript/Javascript and RxJs code

Trying to make sense of rxjs has been a challenge for me, especially when looking at these specific lines of code: const dispatcher = fn => (...args) => appState.next(fn(...args)); const actionX = dispatcher(data =>({type: 'X', data})); ...

Can you provide me with instructions on how to change the background image?

Having trouble with the CSS code I wrote for a background-image. It's not showing up when I set it in my CSS stylesheet. I tested it and found that it only works when written in the body... <body background="Tokyo.png"> ...but not in the styl ...

Fetching information from the database and presenting it in a div using AJAX, jQuery, and CodeIgniter

I am trying to implement a functionality where data from the database is displayed in one div upon clicking a button. Here is my controller : function search_course() { $this->load->view('pages/doctor-search'); ...

What is the most effective method for merging two arrays in JavaScript?

Can a function be created to generate an array like the following? ["0-AA", "0-BB", "1-AA", "1-BB", "2-AA", "2-BB", "3-AA", "3-BB"] This particular function combines two array ...