简体   繁体   中英

How to take a div that is off screen and translate it to the middle of the screen using translateX()

Let me explain a little more in depth. I'm looking to have a div off screen. When a user clicks on a button I want the div to transition onto the screen.

<a href="#" id="button">Click Me</a>
   <div style="position:absolute;left:-100%;width:80%;height:80%;background:yellow; id="block" class="objecttransition"></div>

Here is the JS:

$("#button").click(function(){
 $("#block".addClass("move");
}):

Here is the CSS:

.move
  {
    transform: translateX($$);
    -webkit-transform: translateX($$); /** Safari & Chrome **/
    -o-transform: translateX($$); /** Opera **/
    -moz-transform: translateX($$); /** Firefox **/
  }

.objecttransition
  {
    transition: all 0.5s linear;
    -webkit-transition: all 0.5s linear; /** Chrome & Safari **/
    -moz-transition: all 0.5s linear; /** Firefox **/
    -o-transition: all 0.5s linear; /** Opera **/
  }

My question now is by how much do I move the block to the right to make sure that the block is always in the middle of the screen regardless of the screen size??

I don't know why you're trying to move it into the screen using translateX() when you can just modify the left property to do it:

HTML

<a href="#" id="button">Click Me</a>
<div id="block" class="objecttransition"></div>

CSS

.objecttransition {
  position: absolute;
  top: 10%;
  left: -80%;
  width: 80%;
  height: 80%;
  background-color: yellow;
  transition: all 0.5s linear;
  -webkit-transition: all 0.5s linear;
  -moz-transition: all 0.5s linear;
  -o-transition: all 0.5s linear;
}

.move {
  left: 10%;
}

jQuery

$('#button').on('click', function() {
  $('#block').addClass('move');
});

This actually can be done without any Javascript, anyway here's a working example using jQuery.

<div>Hello!</div>
div {
    opacity: 0;
    position: absolute;
    top: 50%;
    left: 100%;
    width: 5rem;
    line-height: 5rem;
    text-align: center;
    background: red;
    -webkit-transform: translate(-50%, -50%);
    -moz-transform: translate(-50 -50%);
    transform: translate(-50%, -50%);
    -webkit-transition: 1200ms;
    -moz-transition: 1200ms;
    transition: 1200ms; }

div.foo {
    opacity: 1;
    left: 50%;
}
$( document ).on('click', function() {
    $( 'div' ).toggleClass( 'foo' );
});

first of all you might should use

.toggle()

or

.animate()

but to center it via css you have to do some like

.foobar{
    height: 100px;
    width: 100px;
    position: absolute;
    left: 50%;
    top: 50%;
    margin: -50px 0 0 -50px; /* half of height | 0 | 0 | half of width */
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM