Tips for aligning a rotated element with the right edge

My current challenge involves aligning an absolute element (an image) to the right edge of its container.

Under normal circumstances, this alignment works seamlessly. However, when a transformation is applied, calculating the correct left property becomes an issue.

In my search for a solution, I stumbled upon using getBoundingClientRect() to obtain the width and subsequently subtract it from the container's overall width.

If you're interested, here's a demonstration showcasing what I have been working on: JSFiddle

Answer №1

Utilizing getBoundingClientRect is a solid method, however the challenge lies in the fact that applying a CSS left property positions an element without taking into account any rotation calculations. The sequence in which you apply styles does not alter the fact that the rotation is applied relative to the CSS properties, rather than the current position of the rotated element. Therefore, when obtaining dimensions using getBoundingClientRect, you are considering the rotation, yet implementing it on CSS that disregards this factor.

An effective technique to obtain accurate coordinates involves calculating the difference in x values before and after rotation, adjusting the left positioning accordingly. By subtracting the previous dimension's x value from the current dimension's x value (prevDimension.x - dimension.x), you can determine the x difference resulting from the rotation, enabling you to modify newLeft.

For example:

$('#rotate-align').click(function () {
                var prevDimensions = $('.element')[0].getBoundingClientRect();
        $('.element').css('transform', 'rotate(0.99923rad)');
        var dimensions = $('.element')[0].getBoundingClientRect();
        var newLeft = $('#bounds').width() - dimensions.width - dimensions.x + prevDimensions.x;
        $('.element').css('left', newLeft);
});

Sample Link

Another strategy involves determining the x difference based on the disparity in width between the non-rotated element and the rotated one. This calculation utilizes offsetWidth (which ignores rotation) in conjunction with getBoundingClientRect. The difference obtained highlights the amount of width lost due to rotation. It is crucial to consider the transform origin for this computation; for instance, in a centered rotation, halving the width difference provides the x difference, while a different origin would yield an alternative result.

Like so:

$('#rotate-align').click(function () {
        $('.element').css('transform', 'rotate(0.99923rad)');
        var dimensions = $('.element')[0].getBoundingClientRect();
        var newLeft = $('#bounds').width() - $('.element')[0].offsetWidth + (($('.element')[0].offsetWidth - dimensions.width) / 2);
        $('.element').css('left', newLeft);
});

Alternate Example

Answer №2

Check out this JSFiddle link.

When the image is rotated, the bounding rectangle stays fixed at the rotation point instead of moving to the transformed coordinates.

I introduced a 'bcr' <div> element that aligns with the bounding client rectangle.

After rotation, we can adjust the image to its correct position (477 representing the far right of bounds).

If you click the button repeatedly, you might notice a slight issue, but that's just the charm of CSS transforms!

$('#align').click(function () {
        var newLeft = $('#bounds').width() - $('.element').outerWidth();
        $('.element').css('left', newLeft);
});

$('#rotate-align').click(function () {
        $('.element').css('transform', 'rotate(0.69923rad)');
        var dimensions = $('.element')[0].getBoundingClientRect();
        $('.element').css('left',477-dimensions.width-dimensions.left);
        $('#bcr').css('left',dimensions.left);
        $('#bcr').css('top',dimensions.top);
        $('#bcr').css('width',dimensions.width);
        $('#bcr').css('height',dimensions.height);
});
#bounds {
  width:427px;
  height:354px;
  left:50px;
  top:38px;
  border: 1px solid red;
  position: absolute;
}
#bcr {
  width:327px;
  height:254px;
  left:150px;
  top:138px;
  border: 1px solid green;
  position: absolute;
}
.element {
  top: 100px; 
  z-index: 102; 
  line-height: 82px; 
  width: 312px; 
  height: 82px; 
  #transform: rotate(0.99923rad); 
  left: 0;
  position:absolute;
  border: 1px solid green;
}
.element-img {
  width: 100%!important;
  height: 100%!important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="bounds">
 <div class="element">  
  <img class="element-img" src="https://www.google.com/logos/doodles/2014/2014-winter-olympics-5710368030588928-hp2x.jpg">  </div>
</div>
<input type="button" id="align" value="Align right" style="width:100%;" />
<input type="button" id="rotate-align" value="Rotate and align right" style="width:100%;" />
<div id="bcr"></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

Steps for running a function upon activation of a React Router:

I'm currently using Reacter Router to manage the routes of my application. For authentication, I am utilizing an OAuth system that provides my application with the following URL: http://localhost/login-meli?code=1234567890 Every time this particular ...

Can a drag-and-drop feature be created for a hexagonal shape?

The hexagonal grid How can I implement a drag and drop feature for circular elements that will snap to the hexagonal grid shown above? Additionally, I would like to log the starting and arriving coordinates of each element. My initial idea was to track cl ...

Tips for preventing needless re-renders in React functional components when dealing with "static components"

In my React functional component, I have a feature that displays a list of tags and posts along with some static text and decorations. The currently selected tag is stored in a state using the useState hook. Posts are fetched through Apollo's useQuery ...

Is it feasible to create a tabbed layout that is responsive?

Would it be possible to create a layout like this and how would you go about doing it? The container has borders, except at the top where the tabs are located. Only the selected tab should have a border at the top. The text on the tabs should be centered, ...

What is the best way to trigger a JavaScript function to execute as soon as the innerHtml has been modified via Ajax

Utilizing Ajax to dynamically update the content of a div upon clicking a link is my current project. I am seeking guidance on how to call a JavaScript function once the file has been retrieved from the server and the div's content has been replaced. ...

How to ensure MUI DataGrid fills the vertical space without any overflow issues

Trying to implement a MUI DataGrid within a Flexbox layout that fills the remaining space precisely can be quite challenging. Imagine a setup like this: --------------------------- | Header | --------------------------- | Table Header ...

Issue: The error message "articales.forEach is not a function" is indicating

app.get('/', (req, res) => { const articales = { title: 'Test Articles', createdAt: Date.now(), description: "Test Description" } res.render('index', { articales : articales }) }) <div ...

Exploring the Concept of Callbacks in JavaScript

What happens behind the scenes when a function is passed as a parameter in JavaScript and how does the engine recognize it as a callback? ...

CORS - Preflight request response fails access control verification

I've been attempting to send a GET request to a server with the same domain as my local host, but I keep encountering the following error: The preflight request response fails the access control check: The requested resource does not have an ' ...

Is it possible to single out a specific cell with the smart-table feature?

While the smart-table documentation provides instructions on selecting a row of data, it does not cover selecting an individual cell (the intersection of a row and a column). Upon further research, I came across this discussion where the project owner men ...

How can I implement JQuery in JavaScript to enhance functionality on an HTML webpage?

I'm currently working on a website project and I'm running into some trouble with my jQuery library. I've tried implementing the code below, but it doesn't seem to be working. I'm using Notepad++ with Denwer local server. <scrip ...

Maximizing the versatility of components with styled-components and React: A comprehensive guide to incorporating variants

Currently, I am a novice programmer working on a personal project using React for the front-end. I am looking to create a Button component with the styled-components package that can be easily reused throughout the app with some variations in size, color, ...

What is the most effective way to determine if a statement is either false or undefined?

What is the most effective way to determine if a statement is not true or undefined, sometimes without necessarily being a boolean? I am attempting to improve this code. var result = 'sometimes the result is undefined'; if (result === false || ...

jQuery modal window extension

Currently, I am utilizing a jQuery popup plugin that opens a popup window using the anchor's href. For example: <a href="/some/site?hello=hi" class="popup">link</a> There could be an unlimited number of these on my page, each pointing to ...

Clicking on the initial link will in turn prompt clicks on the subsequent links

Can you please provide instructions on how to correctly simulate a click on the remaining links if a click is made on the first link? jQuery('a.one_num').click(function() { jQuery('a.two_num').click(); jQuery('a.three_num&ap ...

Is there a way to get Cesium points to orbit along with the map?

I have a project where I am creating a cesium app and I am facing an issue with the rotational heading of my points. I am using billboards to display custom images indicating this heading, but as I rotate the globe, the points do not rotate accordingly, re ...

Concealing a button in Odoo Helpdesk with JavaScript: a step-by-step guide

For Odoo version 15, I have implemented a JavaScript code that is triggered by the buttons "Accept" and "Deny" in a boolean field within the res users model. The functionality works as expected, however, my current issue is that both buttons appear on the ...

Node.js encountering a SequelizeConnectionError was an unexpected hurdle for the application

I am facing a peculiar issue and struggling to identify the exact source of the problem. Any assistance on this matter would be greatly appreciated. My Node.js application functions perfectly on my local Windows 10 computer. I have also managed to success ...

Having trouble with retrieving data from a JSON file through a service in Angular 4? Getting an "unexpected end of input" error?

I've been attempting to retrieve data from a JSON file stored in the assets folder, but all I keep encountering are errors. heroes.service.ts getPeopleData(): Observable<people[]>{ return this.http.get<people[]>('assets/data/someD ...

How to use jQuery to locate an ID or form outside of its parent element

Is it possible to access an ID or form that is outside of its parent ID? For instance: <ul> <li> <a></a> </li> </ul> <div> <div> <div> <div> ...