hacer que dos elementos html tengan el mismo centro con css in javascript

To make two HTML elements have the same center using CSS and Javascript, you can use the following steps:

  1. Get the dimensions (width and height) of both the elements using the offsetWidth and offsetHeight properties in javascript.
  2. Calculate the center point of each element by dividing the dimensions by 2.
  3. Calculate the difference between the two center points.
  4. Use CSS to position the elements using the transform: translate property and pass in the difference between the center points.

Here is an example implementation:

<div class="element1">Element1</div>
<div class="element2">Element2</div>
74 chars
3 lines
index.tsx
// Get the dimensions of both elements
const el1 = document.querySelector('.element1');
const el2 = document.querySelector('.element2');
const el1Width = el1.offsetWidth;
const el1Height = el1.offsetHeight;
const el2Width = el2.offsetWidth;
const el2Height = el2.offsetHeight;

// Calculate the center points
const el1CenterX = el1Width / 2;
const el1CenterY = el1Height / 2;
const el2CenterX = el2Width / 2;
const el2CenterY = el2Height / 2;

// Calculate the difference between the center points
const centerXDiff = el1CenterX - el2CenterX;
const centerYDiff = el1CenterY - el2CenterY;

// Position elements relative to each other
el1.style.transform = `translate(${centerXDiff}px, ${centerYDiff}px)`;
el2.style.transform = `translate(${-centerXDiff}px, ${-centerYDiff}px)`;
777 chars
22 lines

This will position element1 and element2 such that they have the same center point.

related categories

gistlibby LogSnag