user4284509
user4284509

Reputation:

How to use margin:0 auto in jquery?

I tried to center align a div on click, but this is not working

$().click(function(){
    $(".scale_roll").css({"width" : "80% ","margin":"0 auto"});
});

When I used marign-left:100px it works fine. What is the problem in aligning the div to center using this property in jQuery?

Upvotes: 1

Views: 3574

Answers (5)

Praveen Raj
Praveen Raj

Reputation: 1014

I guess instead of giving "margin":"0 auto" you can give "margin":"auto".

$(".scale_roll").click( function() {
    $(this).css({
        "width": "80%",
           "margin": "auto"
    });
});

This my working Demo

Upvotes: 0

Rajan Goswami
Rajan Goswami

Reputation: 769

You have not spelled your click function correctly.

$().click(function(){
$(".scale_roll").css({"width" : "80% ","margin":"0 auto"});
});

Upvotes: 0

Luthando Ntsekwa
Luthando Ntsekwa

Reputation: 4218

Move div to the center and then back to its original position. Please click "Run code snippet" below

$(".scale_roll").click(function(){
   if($(this).width() == 100)
       $(this).css({"width" : "80% ","margin":"0 auto"});
   else
       $(this).css({"width" : "100px ","margin":"0"});
});
.scale_roll{
  width:100px; 
  height:100px;
  background-color:green;
  color:#fff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="scale_roll">Click Me<div>

Upvotes: 0

areim
areim

Reputation: 3739

Your target in click function is empty, it should be something like this:

$(".scale_roll").click( function() {
    $(this).css({
        "width": "80%",
        "margin": "0 auto"
    });
});

working DEMO

Upvotes: 0

Milind Anantwar
Milind Anantwar

Reputation: 82231

TYPO.

auto 0 should be 0 auto:

$(".scale_roll").css({"width" : "80% ","margin":"0 auto"});

Upvotes: 3

Related Questions