jquery animate with center responsive

998 views Asked by At

I'm trying to animate a box to the center of the screen's width using jquery with .css that will respond to browser size adjustment but I can't seem to get it to respond right in the center without refreshing the browser. Here's the code:

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

.box {
    position: absolute;
    border: 1px solid red;
    width: 300px;
    height: 300px;
}

$(function(){
    $(".box").css({left: $(window).width() / 2 - $(".box").width() / 2})
    .animate({left: '-=0%', top: '100px'},700);
});

I tried using .css({left:'50%'}) that will respond to browser size but now the box is not centered.

3

There are 3 answers

1
Tahir Ahmed On BEST ANSWER

Based on my understanding of your problem as I mentioned in comments, this is a solution that you can use.

$(function(){
  $(".box").css({left:'50%',transform:'translateX(-50%)'}).animate({top:'100px'},700);
});

Reference: Centering Percentage Width/Height Elements.

0
Rizky Hajar On

If you still need style using jQuery you can try use left again .css({left:'50%'}) then add negative margin left 50% of box .css({marginLeft: ($('.box').width() / 2)*-1})

so summary of animated code

$(".box").css({left: $(window).width() / 2 - $(".box").width() / 2})
.animate({left: '50%', marginLeft:  ($(".box").width()/2)*-1, top: '100px'},700);
0
Thiago Avelino On

You can center by using this css example: http://www.thesitewizard.com/css/center-div-block.shtml

code snippet:

#box{
      ...
      margin-left: auto ;
      margin-right: auto ;
    }

As you're using box. I believe you want something like a modal window. So, you can use jquery UI for that: https://jqueryui.com/dialog/