简体   繁体   English

如何在jQuery中使用margin:0 auto?

[英]How to use margin:0 auto in jquery?

I tried to center align a div on click, but this is not working 我试图使div居中对齐,但这不起作用

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

When I used marign-left : 100px it works fine. 当我使用marign-left100px它工作正常。 What is the problem in aligning the div to center using this property in jQuery? 在jQuery中使用此属性将div居中对齐有什么问题?

TYPO. 错字

auto 0 should be 0 auto : auto 0应该是0 auto

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

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 工作演示

Move div to the center and then back to its original position. 将div移到中心,然后回到其原始位置。 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> 

You have not spelled your click function correctly. 您尚未正确拼写您的click功能。

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

I guess instead of giving "margin":"0 auto" you can give "margin":"auto" . 我想可以给"margin":"auto"代替"margin":"0 auto" "margin":"auto"

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

This my working Demo 这是我的工作演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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