Ask Your Question
2

How can I make an element move to the top right corner, starting from any position?

asked 2023-06-08 06:27:37 +0000

pufferfish gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2023-06-08 06:50:02 +0000

ladyg gravatar image

You can use CSS position property to achieve this effect. Here's an example:

HTML:

<div class="box"></div>

CSS:

.box {
  position: relative;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  width: 100px;
  height: 100px;
  background-color: red;
  transition: all 1s;
}

.box.moved {
  position: absolute;
  right: 0;
  top: 0;
}

JavaScript (JQuery):

$(document).ready(function() {
  $('.box').click(function() {
    $(this).addClass('moved');
  });
});

Explanation: - The HTML code creates a div element with a class of "box". - The CSS code sets the initial position of the box element to be in the center of the screen using the "left" and "top" properties with values of 50%. The "transform" property centers the box element both vertically and horizontally using the "translate" function. The "width", "height", and "background-color" properties are used to style the box element. The "transition" property adds a smooth animation effect when the box element moves. - The ".box.moved" CSS selector updates the position of the box element when the "moved" class is added to it. The "position" property changes to "absolute" to position the box element at the top right corner using the "right" and "top" properties. - The JavaScript code adds a click event listener to the box element. When the box element is clicked, the "moved" class is added to it, triggering the CSS animation to move the box element to the top right corner.

This code can be adjusted to fit different element sizes and positions.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-06-08 06:27:37 +0000

Seen: 23 times

Last updated: Jun 08 '23