Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

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.